Hello Devs👋, We all know that NodeJS is neither a programming language nor a framework, it goes beyond that. NodeJS is a Javascript runtime environment built on Chrome's V8 javascript engine. It is lightweight, fast and data-intensive. It also consists of many built-in modules, and to understand that, we have to first understand the architecture and internal working of NodeJS, so just let's dive deep into it.🚀
The flow of NodeJS starts with the client, the client requests the server, and this is where the flow starts. NodeJS uses the concept of thread. A thread is a sequence of instructions that the server needs to perform. As soon as the client makes the request, this request is placed into the event queue. The event loop will pick up these requests and call the action associated with these events and then the response is sent to the client.
There are two types of requests:-
Blocking Requests: This works on asynchronous concept. Asynchronous means executing a callback function. As NodeJS is an event-based architecture so callbacks are executed as soon as some work is done. The single thread does not work with requests it sends requests to another thread which resolves the request and then it is accessible.
Non-Blocking Requests: This means working with multiple requests without blocking the thread for single requests. In this, the program does not block the execution of further operations.
The event loop is one of the most important feature of NodeJS. It is an indefinite loop that continuously receives the requests and processes them. It is responsible for executing the callbacks and network I/O associated with the events. Most of the work is done in an event loop. All the code inside the callback is executed by the event loop.
In the case of blocking operations, the event loop requires a thread from the thread pool to get the work done associated with the callback and then it returns the response to the event loop and then it returns the result to the client.
The thread pool is also one of the most important feature of NodeJS. Though NodeJS is single-threaded it internally maintains the thread pool. When blocking requests are processed in an event loop it checks for available threads in a thread pool. The available thread is assigned to the client's request which is then processed and then send back to the event loop, and then the response is sent to the respective client.
But now the question is how many threads are there in a thread pool? 🤔
By default thread pool size is 4. The thread pool size is changeable. Its size depends on the CPU's core and it varies from system to system.
So, this was NodeJS architecture and how it works under the hoods.
Okayyy, See you in the next blog...Till then...
Happy Coding🚀!!.....