Understanding node.js

Essentially Node has an approach of making I/O operations non-blocking. All the I/O operations run independently and generate an event when they are done.  Node follows an execution model of having an event loop (a concept existing in JavaScript) that handles events that are generated by I/O operations ( like database, HTTP requests, file I/O s).  Whenever an I/O operation occurs, the event loop handles the event and processes it by converting it into callback invocation. With this mechanism, the I/O operation is handled in the background and the callback gets executed when the required data is available. This is also called as  asynchronous way of handling events.

Node expects that there is no fixed time within which the I/O is performed. So instead of waiting for the result, Node generates an event (which are in-turn handled by callbacks) and hence the tasks get performed in “parallel” (nothing to do with multi-core and true parallelism;  in fact Node can’t take advantage of multi-core as its a single threaded event loop).

In the hello world example, we have a HTTP server listening on port 8888. When the server receives an I/O activity (http GET request) an event (request) is fired which is tied to callback (anonymous function(request,response) ) which in turn prints ‘Hello World’. Node uses Linux libraries like epoll, select (as does Python Tornado) to get notified that a user has made a connection with the server.

Let’s understand the concept with an example of database call being made in the web server.

var result = mysql.execute(query);
console.log("I am done");

The above code is synchronous in nature. If a database call takes 15 secs to run, HTTP server is blocked. One db request like above can block the web server and as a result any other following requests can’t be served until the first request is complete.

Solution? Let’s try asynchronous then:

mysql.execute(query, function(result) {       
console.log("callback");
 });
console.log("I am done");

In the above code, database request is made async with the help of callback. So whenever the database query results are available, an event is generated that is handled by the callback & “callback” string is printed out, but before that the event loop moves ahead and prints “I am done”. It’s crucial to note that mysql.execute function itself should be written in an async manner for this to be successful.

Almost all the node api’s are async in nature and can be taken advantage of. But how do I develop my async function? Hmm.. you must read my next post 🙂

2 thoughts on “Understanding node.js

  1. Does Node.js provides async model for all services e.g. networking, database?
    How is the async implementation in the Node.js event loop? Is it a single thread or a multi-threaded? Why should I move to async model?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.