NodeJS, Single-threaded? Not Single-threaded

I still heard workmate saying that NodeJs is mono-thread. Well, it’s not quite true…but not quite wrong either.

img-211161171f3

 

 

 

 

Node’s heart is its javascript engine, which is mono-threaded. But other parts of node are in C++ and run in a thread pool.

Let’s imagine a basic Rest API code which receives a request, gets data from a database and returns those data in json. The exchange with the DB is excuted by a thread of the pool so that the javascript thread is able to process another request in parallel.

The thread is often named as the loop event thread and it’s genuine role is to process events. A schema, that can be find in multiple places on Internet, offers a good overview of threads interaction:

nodejs20for20dotnet

Have you notice the use of callbacks ? Whenever event loop calls an asynchronous function has the result, it calls the callback with the result. Behind an asynchronous function, you can find a C++ pool thread code.

Here is another Internet schema to clarify this:

threads-in-node-ja_

Node manages all the plumbing between javascript and C++: all this is unseen by the developer. Yet, Node developer must have this in mind to write effective code. My next posts will explain why and how to write scalable code.

See you and have a nice code. 🙋