What is node.js?

I’ve recently decided to write a book about node.js. I don’t feel like a lot of books out there (on any technology) cover real-world scenarios. Most of them are introductions to languages or deep-dives into a single aspect of a language or technology. There are very few books that cover real-world application development scenarios to include things like process, build, sample application, and deployment. A good example of the type of book I’d like to write is Agile Web Development with Rails.

Below is an excerpt from one of the first chapters of the book. This is *very* rough draft, but I thought I would share because it may be useful for anyone beginning in node.js development.


What is node.js?

Node.js is a server-side JavaScript environment which provides evented asynchronous I/O and a minimalistic set of core features. In the beginning, node.js combined v8 with libev. Unfortunately, libev is an evented I/O library for Unix-based systems only. Eventually, libev was replaced with a higher-level abstraction library called libuv which allows node.js to run on Unix-based systems and Windows. In 2011, Microsoft began contributing to node.js to bring it to the Windows platform. More recently, libuv removed libev as a dependency.

The key concept for node.js is evented I/O (mostly network-based) operations. This is handled via an event loop. Although understanding the implementation details of event loops can be pretty complicated, the idea is fairly simple. Let’s analogize.

Try to think about an application as a fast food restaurant. A cashier is patiently waiting at the register. A customer walks up to the register and places an order. The cashier hands the order off to the kitchen and maybe fulfills the customer’s drink order before returning to the register. Another customer arrives and places an order, initiating the same scenario as before. A third customer is walking to the register, but just before the customer reaches the register a cook dings a bell and the cashier steps away to grab the first order and hand it to the customer. The cashier then begins taking the third customer’s order. Midway through the order, the second customer’s order is ready. Because the cashier is not rude (maybe this is in Canada?), the third order must be completed before the second customer’s order can be handed back to the customer. But, the cashier can easily hand over the second customer’s order before filling the third customer’s drink order. Eventually, the third customer’s order is fulfilled and there are no more customers. The cashier waits patiently.

It may sound strange, but the above scenario is a simplification of an event loop. We see things like this every day. New node.js developers seem to have a hard time either understanding the event loop or understanding where it comes from. Take the following example, for instance:

function main(){
  console.log("Hello, world!");
}

main();

There’s a little more going on in this example than the standard obligatory printing of “Hello, world!” I’ve wrapped the output line in a function called main and subsequently called that function. If you run this file, you’ll see that it prints out “Hello, world!” and exits. There is no event loop because we haven’t told the runtime to listen to or emit any events.

There are a couple ways we can initiate an event loop. Possibly the easiest way to visualize this is to use the standard JavaScript setInterval function to cause our application to write out “Hello, world!” every 250ms. To kill this application, you’d need to press Control-c.

function main(){
  console.log("Hello, world!");
}

setInterval(main, 250);

The above example is technically an event loop, although there aren’t really any events going on other than the setInterval function. Another way to initiate an event loop is to bind to or set up any event which interacts in some way with a file handle. In Unix, nearly everything is considered a file, so this would mean binding to a socket, file descriptor, or even screen input:

// respond to the SIGINT event
process.on('SIGINT', function(){
    process.stdout.write('\nHandling SIGINT event!\n');
    // cleanly exit with non-error status
    process.exit(0);
});

// listen to events on standard input
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
  process.stdout.write('Hello, world!\n');
});

// Start reading from stdin so we don't exit.
process.stdin.resume();
console.log('Type anything and press ENTER...');

In the above example, process.stdin.resume() causes node.js to continually monitor the readable standard input stream for data. Binding a listener to watch for ‘SIGINT’ does not cause node to create an event loop on its own. Play around with this last example to get an idea of how the event loop works. If you’re interested in how libuv creates and maintains an event loop, there is a free uvbook available which dives into the internals of libuv.