Multi threading and multiple process in Nodejs

Posted By : Renu Yadav | 30-Nov-2018

Nodejs uses a one single javascript thread. So there is a question about how the node js handle the multiple requests. Like in our program we uploading the file and files size is big. File uploading taking too much time to upload. In the below code you can see that writeFileSync method block the other process because it is the synchronous function. the other process will run after the completion of the writing process in file.

if(url==='/message' && method===POST){
	fs.writeFileSync('message.txt', 'Dummy');
	res.statusCode=302;
	res.setHeader('Location','/');
	return res.end();
}

 

In this process, the next request will block because the thread is not free to handle the request. Nodejs have already had the solution for that is Event Loop. The event loop is automatically started by nodejs. You do not need to write the code to start the event loop in nodejs. Event Loop handles the event callbacks code which finished fast. 

INCOMING REQUEST 

                 |                                                          |------------>    EVENT LOOP      ( Handle Event CallBack)

|Your Code               Single Js Thread        ------|                                   |     

                                                |                                                               |                    

                                                |------------->     Fs                                   |

                                                                           |------------>     Worker Pool -------->    Different Threads

                                                                                            ( Do the heavy Lifting )           

                                                                                                      

In the above diagram, you can see that When incoming request come to the node js. The single thread sends these request to the event loop. The Event loop is aware of all the callbacks and executes the set code. Event Loop executes all events one by one. Files have uploading process is send to the worker pool. Worker loop is handled by the nodejs automatically. All long taking process will handle by the Worker pool. Worker pool is totally detached to your javascript code. It is run on different threads. After complete, the process the wordker pool triggers the callback function and event loop process the callback function of the file and end the event loop. 

In Nodejs, Event loop plays the important part to the handle the all request without blocking the other process. Event loop makes the nodejs fast and callback function also play the important in the process .

 

 

 

About Author

Author Image
Renu Yadav

Renu is an Associate Consultant -WordPress in Oodles. She likes watching movies and reading books.

Request for Proposal

Name is required

Comment is required

Sending message..