Learning About Node.js

Other server-side JavaScript environments are available; however, Node.js (commonly now just referred to as Node) is by far the most popular and has the best cross-platform support (Windows, OS X, and Linux). Because of this popularity, Node is the JavaScript environment discussed in this book.

One of the core ideas of Node is that all I/O should be nonblocking. This means any time the server waits on some data or some input, it shouldn’t prevent the execution of other code. The way that Node handles this is through the use of callbacks, which are executed automatically when the resource that was blocking becomes available. This is often referred to as evented programming. It’s something that JavaScript programmers are familiar with because it’s the way that most user interfaces (including web pages) are programmed: You add an event listener with a callback that gets called when that event is triggered.

The reason it’s essential to write nonblocking code in Node is that Node is single-threaded, meaning that there is only a single thread of execution at a given time. If the code stalls for any reason, the entire server stops taking requests. This might seem like a disadvantage, but by being single-threaded, Node can handle a huge number of concurrent requests without massive amounts of memory usage. Being single-threaded also means that Node doesn’t need to switch contexts between threads, which provides a performance boost. Combine this with the speed of ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.