Skip to main content

Node.js

What is Node.js ?

Node.js is a JavaScript runtime environment built on the V8 JavaScript engine, the core of Google Chrome, which allows developers to run JavaScript on server side across platforms.

Motivation

Before Node.js, traditional web servers such as Apache used one thread per connection (improved by introducing Apache MPM Worker). Under massive concurrency scenarios, however, such model takes up memories compared to a single-threaded model and has overhead during context-switching.

So for use cases such as server that executes large concurrent and non-blocking tasks (e.g massive concurrent file I/O or database queries), single-thread approach might be a better model.

To take advantage of single-thread model, event loop model that utilizes callbacks for each task is adopted. Such model allows users to write more intuitive non-blocking codes as shown below.

readFile('/file.md', () => {
console.log(data) // Logs after finish reading without blocking following works
});

moreWork() // This can get executed before file content is completely read and printed out (non-blocking)

There were frameworks such as Twisted (Python) and EventMachine (Ruby) that leveraged the event loop model, but such frameworks were somewhat confusion to combine and work with other libraries. Luckily, JavaScript is built in a way that works perfectly with the model: it's single-thread, callbacks get executed when user input event occurs, and has features such as anonymous functions and closures, etc.

So Node.js was proposed to provide a purely evented, non-blocking infrastructure to script hightly concurrent programs.

The design goals are (excerpted from Ryan Dahl's, creator of Nodejs, presentation):

  1. No function should direct perform I/O. There must be a callback.
  2. Low-level.
  3. Stream everything: never force the buffering of data
  4. Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections.
  5. Have built-in support for the most important protocols: TCP, DNS, HTTP, etc.
  6. Support HTTP features: cunked request/response, keep-alive, etc.
  7. API should be familiar to client-side js
  8. Platform independent
info

A presentation delivered by Ryan Dahl, creator of Nodejs, presented Node.js back in 2009 which gave a brief introduction into the design background and philosophy of Node.js.

Node.js Architecture

Reference