Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How many threads does Node.js actually create ?

  • Last Updated : 06 Oct, 2021

Node.js is a cross-platform JavaScript runtime environment which helps to execute and implement server side programs. Node supports asynchronous processing of code, which leads us to the result that it is a single threaded platform. Let’s discuss in detail what is meant by Node being single threaded and why does it follow this method.

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.

Single threaded working of Node

This method is considered to be highly efficient, but there is a drawback with this method too. When we have a lot of CPU-intensive tasks that require synchronous processing, this method won’t work as it will take a very long time and block the code. Since JavaScript and Node weren’t made for CPU tasks, this is an exceptional case and will be handled differently by using worker threads.



Example: Let’s consider an example to understand how event loop works.

Javascript




// Simple JavaScript Code to show Event
// loop demonstration for Node
console.log("Geeks");
setTimeout(function cb(){
    console.log("Geeks");
}, 3000);
console.log("For");

When we execute the given code, the output will be as given below.

Output:

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.

So to summarize, Node and JavaScript are developed to be single-threaded, which helps them to be time-efficient and save memory.

References: https://www.geeksforgeeks.org/why-node-js-is-a-single-threaded-language/

My Personal Notes arrow_drop_up
Recommended Articles
Page :