Benjamin van der Veen

I live in Portland, Oregon. I work as a user experience designer at Emma.

Take a look at my portfolio, follow me on Twitter @bvanderveen, or email me at .

Node does IO.

Consider these few lines from Mark McGranaghan’s post ClojureScript and Node.js:

(defn handler [_ res]
  (.writeHead res 200 (.strobj {"Content-Type" "text/plain"}))
  (.end res "Hello World!\n"))

Here is the equivalent JavaScript:

handler = function (_, res) {
    res.writeHead(200, { "Content-Type" : "text/plain" });
    res.end("Hello World!\n")
}

This is a Node.js HTTP request handler. When a request comes in, this handler function is called. It writes an HTTP response header, sends a bit of body, and calls it a day. Nothing fancy.

The variable res is unnecessary. This code doesn’t care about res-the-object; that’s just syntactical noise. What this code actually cares about is writeHead and end, the behaviors res-the-object provides.

The devils and angels bicker:

That isn’t fair, because what we have here is a writer pattern, which necessarily implies state—both writeHead and end return void. There is IO going on here, and functional programs don’t do IO! We need OOP!

or,

Implement a writer monad! Then abstract that idea it so the request handler returns a data structure which represents the response! This parallels the request data structure nicely and it’s so beautiful this way.

Who cares. Node does IO. Abstract it, that’s what it’s there for.

Copyright © 2012 Benjamin van der Veen. atom feed