How many threads does Node actually create ?
Download and install Node.js: Download Node.js
Earlier Development of Node: When Node was initially being developed, it followed the paradigm of one thread per request. This means that whenever a user made a request to the server, or requests were made from the database … a separate thread was created to complete that request. The problem with this method was that when requests spent their time on I/O operations, it leads to wastage of resources linked to these threads. This also resulted in larger time periods of execution as this was synchronous processing.
Using Single thread and Concept of Event Loop: To overcome this problem, Node adopted a single thread system with event loop and asynchronous I/O operations. Using a single thread allows Node to execute one process at a time while the processes that take longer time than usual are handled by Node API and event loop. Event loop uses callbacks to return outputs from functions that were being handled by Node API and the tasks continue to execute normally till the whole code is processed.
Example: Let’s consider an example to understand how event loop works.
When we execute the given code, the output will be as given below.
Geeks For Geeks
The reason for this output is the execution of the setTimeout() function being handled by Node API. Thus, the timeout will continue to execute separately and the call stack will continue to execute other statements asynchronously. To know more about how Node prevents blocking code, check out this article.