Why Node.js

Why Node.js

There has been a buzz about NodeJS in the recent past. Javascript on the serverside? You gotta be kidding me right! Well NodeJS is “a set of bindings to the V8 javascript Virtual Machine. It allows one to script programs that do IO in javascript”

I have been digging into it over the past few days. Before starting off learning I wanted to know whether its worth the effort. I mean we have so many options when it comes to server side scripting. Theres PHP, Ruby On Rails, Django on Python and so many other alternatives. But what seperates Node from these traditional languages/frameworks is its “event-driven, non blocking IO”...err what! Well basically most of the web applications spend most of their time waiting for IO. Thats what is the bottleneck in performance for (most) of the web applications. So lets dig a little deeper into non blocking IO

Consider an example of fetching data from a database

In the synchronous model you might write something like

request = query(‘SELECT * FROM database’);

At this point the program pauses, the program interacts with the database and the query is fetched and data is returned. For a database with a lot of records this pause can be long! During this if there are new requests being made multiple threads are created to serve multiple simultaneous clients. Each thread requires a execution stack and thus they can suck up resources quickly. Also if all threads are busy some requests will be dropped!

In Node the query would be something like

query(‘SELECT * FROM database’, function(result){
//operations on result
});

The asynchronous model we have a callback associated to the event. The result of the query is provided to the callback function that is fired asynchronously when the fetching is complete. Thus the server can continue executing other independent statements and will return (almost) immediately to the callback function once the request is complete.

The rewards for this slight complexity is immense because there is a drastic improvement in concurrency. Also, with Node, since we are using Javscript on both the server as well as the client side, we can have the same developers using the same tools! But given that the project is still nascent there is a lack of documentation. Hopefully the horde of javascript developers will take care of that.