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?
But I heard it is a Web Server?
Why is it so popular?
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.
- It has lambdas, useful for splitting programs into small parts.
- It has nothing else for handling concurrency, so there’s less confusion.