Skip to content

node.js & socket.io fun

I recently had the extreme pleasure to use node.js and socket.io on a project. Here are some insights.

Objective

So the objective of the project was to read data from the _changes feed of our CouchDB cluster (hosted by Cloudant) and publish the data to a widget which we can use to display a constant stream of "what are people doing right now".

The core of the problem we faced was not just taking this stream of data and feeding it on to a page, but since we'll deploy this widget to our homepage we needed to make sure that no matter how many clients see it, the impact on the database cluster is minimal; for example, it would be a single client (or down the road up to three for failover) who actually read data from the cluster.

After shopping around for a technology to use, it became obvious that we needed some sort of abstraction because of how the different technologies (e.g. comet, websockets, ajax longpolling, ...) are implemented in different browsers. We decided to build this project on top of socket.io — pretty much for the same reasons most people go to jQuery, prototype or dojo these days.

jQuery post requests with a json response, sans eval()

I know some of you out there are probably tired of jQuery and people raving about it's goodness, but bare with me! Because jQuery never ceases to amaze me — especially when I haven't looked at it — or client-side JavaScript code in general — in a good year or so.

Refactoring

I've been refactoring some of my old JavaScript libs on a project and I noticed that I had used evil eval() all over the place to parse the JSON from our API. Guess we all know that this is not just a security issue since it allows code execution, but also a performance hit. And here's how to get around it. :-)

A codesnippet to automatically parse a JSON response from a $.post-request:

    $.post(
      '/the-url-post-to',
      data,
      function(json) {
        // handle response
      },
      'json'
    );

Note: The 4th parameter 'json' in $.post(). Magic.

Fin

That's all.