What is Node.js?

It took me some time to get my head around the peculiarities of Node.js so here’s my take on explaining it.

What is Node?

Node(.js) is a program that allows you to run programs written in JavaScript.

But I heard it is a Web Server?

Well a Web Server is a program; you can write one in JavaScript with Node.

Why is it so popular?

Well web developers like to create tools in JavaScript because they are using that language already for programming the browser. For that reason it is also a compelling web server. Some frameworks even allow you to run the same code on the server and the browser. But Node has another advantage.

How come Node beats established web servers?

Node uses a novel approach at dealing with concurrency, that is all the requests and responses a web server needs to process.

So how does Node deal with concurrency?

Well it’s like comparing a large crossing to a roundabout. If a crossing is complicated and busy it needs traffic lights to start and stop the flows that would otherwise collide. With a roundabout however, all flows merge into a large loop and traffic ramps off at the various exits.

Another analogy is a restaurant serving several customers. To deal with all the cooking involved you could:

  • Have multiple kitchens. This is like multiple processes.
  • Have several cooks working in the same kitchen. This is like multithreading.
  • Split the work into¬†small steps that complete quickly. When there is waiting involved (for the oven to finish or water to boil) move on to the next task and continue when the waiting is over.

Traditional web servers use multiple processes and multithreading. The third option is obvious for cooking but not for web servers.

The main downside of each method is:

  • Multiple processes requires a lot of memory and switching and communication between processes requires considerable CPU time.
  • Multithreading is hard when resources are shared. Also each thread requires memory and switching requires CPU time.
  • Splitting programs into small steps requires a language to split code into small parts while still being able to see the flow of tasks.

To be fair Node is not the first web server doing things this way, but it sure made it popular.

Why JavaScript?

Well, besides being able to use the same language in the browser JavaScript has two advantages:

  • It has lambdas, useful for splitting programs into small parts.
  • It has nothing else for handling concurrency, so there’s less confusion.