In this article, we will take a look at Nodejs Architecture and How nodejs works behind the scene.
So, let's get started...
Node.js Architecture - A complete guide
In order to work properly, the node required some dependencies:
The V8 and LIBUV handle the majority of Nodejs operations.
What is V8 Engine?
The V8 engine is what converts Javasciprit code into machine code that a computer can actually understand.
What is Libuv?
Libuv is an open source library with a strong focus on asynchronous IO, this layer is what gives node access to the underlying computer operating system, file system, networking and more.
What is Event loop and Thread Pool?
Besides that, libuv also implements two extremely important features on NodeJS which are the event loop and thread pool.
In Simple terms, the event loop is responsible for handling easy tasks like executing callbacks and network IO while the thread pool is for more heavy work like file access or compression or something like that.
Understand Node Process and Threads:
What is Node Process?
When we use node on computer in means there is a Node Process running on that computer, and the process is just a program in execution.
What is Thread?
The Thread is a basically just sequence of instructions.
Now as nodejs runs on single thread, which makes it easy to block applications, so if you run your node application it will run in just a single thread, without considering how many users you have 10 or 10 million accessing your application at the same, so here you need to be very careful to not blocking that thread.
Let's see what happens when in a single thred when you start your node Application:
According to the above chart, when the program is initialized, all the top-level code is executed, except the code which is on the callback function, then all the required modules and then all the callbacks are registered, and at last, the event loop finally starts running.
What is an Event loop?
The event loop is where most of the work is done in your app, so it's really the heart of the entire Node Architecture.
Here some tasks are actually too heavy, they are too expensive to be executed in the event loop because they would then block the single thread, and so, that’s where the thread pool comes in, which just like the event loop, is provided to NodeJs by the libuv library,
So, the thread pool gives us four additional threads, that are completely separate from the main single thread.
We can actually configure it up to 128 threads, but usually, these four are enough, so these threads together formed a thread pool, and the event loop can then automatically offload heavy tasks to the thread pool, and all this happens automatically behind the scenes, its not us developers who decide what goes to the pool and what doesn’t.
Heavy Task (Files system APIs, Cryptography, Compression, DNS lookup)