Code and Craft

A blog by Amy Cheng

Reflections on Node.js

I've been using Node.js for a few weeks now. I wrote a Flickr back-up utility and a Wikipedia scraper (which I wrote about here).

Node.js seemed like this mysterious thing. What does "server side javascript" mean? After doing two projects with it, I'm getting a better grasp of what it is and what it can do. Things like scraping the web, serving an API, and being a web server for static assets. There were a few things that took me some time to wrap my head around:

Asynchronicity and avoiding race conditions

A race condition happens when your functions finish in the incorrect order. Node.js functions run asynchornicty and are non-blocking. I was used to writing and executing functions that ran one after enough. If there was an error, the entire app would stop working. This isn't the case with Node.js. Functions that dealt with the filesystem or making HTTP requests would occur asynchronously; they would continue working while other functions did their thing.

Avoiding callback hell and spaghetti code

The way to avoid race conditions is to properly have callbacks. That is once a function finishes doing its thing, it does a callback to another function (or trigger an event, but I haven't gotten to the point in using events in Node.js). Callback hell occurs when you nest functions within functions within functions.

I'm a stickler for clean code, and so far have avoided callback hell by naming my functions and writing modular code.

Dependencies galore

Node.js is pretty barebones. I found myself adding lots of dependencies because I didn't want to figure out solutions to problems others have solved (things like calling the Wikipedia api, figuring out MIME-types for serving assets with a Node.js server, and parsing dates). It's very easy to go nuts with the plugins.

An Aside: Things I like about Node.js

« Scraping Wikipedia for Recent Contributions, a project post-mortem My first Girls Who Code club meeting »