Nodejs process – Is it always single threaded? How efficient is it?

A NodeJS process as we have come to know is considered and is, a programmatically single thread of execution. But that said, we also have complex and complicated system/workflows running in NodeJS without any problem. So How does this work?

The MultiThread behind!

The NodeJS is nothing but javascript running over the v8 engine of Google. As we all know, the v8 engine is based on c++ and c++ supports multiple threads. True there is one main global execution thread in our node js process that is triggering out multiple calls and waiting for call backs. But the function calls which are dependant on asynchronous tasks like network i/o or disk i/o are usually given to a separate c library behind (libuv) and this spawns separate threads for these tasks and report back to the main global execution thread when its done. So a nodejs process code which updates 5 files with different sets of data, might actually in reality be having 6 threads but as a programmer you are controlling only the main thread and you can receive notifications of other threads in that global context thru callbacks! Neat!

So for any application (web) where we are dealing with 10k simultaneous users can easily be served using a good powerful server without any lags using NodeJS servers. (or even more,.. this is just a ballpark).

There is also parallel executions possible in NodeJS using fork(), just on the same lines as C/C++ and we will see it explained in a future post.

Leave a Reply

%d bloggers like this: