How Nodejs works?

The client makes a request to the server.
The request goes to the server.
First, the request gets queued in the event queue.
After that, the request is sent to the event loop.
The event loop continuously monitors the event queue for requests
and processes them one by one.
There are two types of requests:
Blocking
Non-blocking
The event loop first checks whether a request is blocking or non-blocking.
If it's non-blocking, Node.js processes it and sends the response to the user.
If the request is blocking, it is sent to the thread pool.
What is a thread pool?
A thread pool is a collection of threads where tasks are assigned to individual threads.
When a task is completed, the thread returns to the thread pool and waits for another task.
How many threads are present in the thread pool?
The number of threads in the thread pool depends on the operating system and hardware.
By default, Node.js creates a thread pool with a configurable size,
typically based on the number of available CPU cores.
Is Node.js single-threaded?
Yes, Node.js is single-threaded, meaning it runs JavaScript code on a single main thread.
However, for blocking I/O operations or CPU-intensive tasks, it offloads them to the thread pool.
Default thread pool size in Node.js
The default size of the thread pool in Node.js is typically determined by the formula:
4 × (number of CPU cores available on the system)
Subscribe to my newsletter
Read articles from pragalbh srivastav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by