Monday, October 18, 2010

Long Polling with Node.JS and Express

When I write tools or algorithms that I want other people to improve or understand, I use Python. When I am writing them for myself, because I'm in a hurry, I use Lisp. (I think in closures and the application of functions, which I occasionally force myself to re-express in classes and methods.) Since Python's Lambda syntax is a great disappointment to me and its father, Guido van Rossum, I occasionally pine for the weird cousin of Lisp we call JavaScript.

JavaScript is regarded by Lisp hackers as Lisp without parenthesis, shackled by the problem domain of browser scripting. It's a great, powerful language for people who think in closures, but until the recent introduction of libraries like jQuery, it's also shackled to really cruddy libraries. When Google released V8 under the BSD license, I think many of us immediately ran to check out the source, write a partial general purpose environment, then wandered off to do better things. Like bugfixes for MOSREF. *cough*

Ryan Dahl, unlike the rest of us, stuck with it, and fused V8 with the similarly fascinating libev to produce a JavaScript environment for I/O-centric problems that don't live solely within the browser. The resulting Node.JS strikes an interesting balance between minimalism, functionality, and performance thanks to its reliance on existing projects with great characteristics.

When I encounter a new language or framework, I fall back on a set of problems dear to my heart -- writing a MUD server. With web frameworks, lately, this has been simplified down into "can I write a long-polling message wall with it?" Simple problem, tends to break most simplistic web frameworks simply because requests are often deferred, waiting for an update.

Here it is in Node.JS, using Express, about 50 lines of overcommented code. I'm sure it could be written faster, but probably not as concisely.

Next up, making a kobold walk around a message board.. ;)

No comments:

Post a Comment