How to handle Child Threads in Node.js ?

Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.

But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.

Child Process in Node: The child_process module gives the node the ability to run the child process by accessing operating system commands.

Example: Filename: parallelProcess.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Do any work in parallel to main
// event loop or main process
console.log('Child Process Starts')
setTimeout(() => {
    console.log('Data proccessed')
}, 5000)

chevron_right


Filename: main.js



filter_none

edit
close

play_arrow

link
brightness_4
code

const { fork } = require('child_process');
   
// Fork another process
const child_process = fork('./parallelProcess.js');
  
// Data we may need to send to the child process
const data = {} 
  
console.log('Before process')
  
// Send the data to forked process
child_process.send({ data }, function(){
    console.log('Sending data')
});
  
// Listen to forked process 
child_process.on('close', (result) => {
    console.log('Child process terminated and returned');
});
  
console.log('After process')

chevron_right


Output:

Before process
After process
Child Process Starts
Data proccessed
Child process terminated and returned

Worker Threads The worker_threads module enables the use of threads that execute JavaScript in parallel. Worker’s threads are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work which can be done better using Node.js built-in asynchronous I/O operations.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

const {Worker, isMainThread, parentPort} 
            = require('worker_threads');
  
if (isMainThread) {
  
    // Main code, only executed for main thread
    const worker = new Worker(__filename, {
        workerData: {}
    });
  
    worker.on('message', (m) => console.log(
                  'Thread send message:', m));
  
    worker.on('error', () => console.log('Error'));
    worker.on('exit', () => {
        console.log('Worker exit')
    });
} else {
  
    // Worker thread code, only execute
    // for working thread.
    setTimeout(() => {
        parentPort.postMessage('Hello World!');
    }, 3000)
}

chevron_right


Output:

Thread send message: Hello World!
Worker exit

The process has its own memory space on other hand, threads use the shared memory space. Thread is part of the process. Since worker_threads make new threads inside the same process it requires fewer resources.

Reference:
https://nodejs.org/api/child_process.html
https://nodejs.org/api/worker_threads.html




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.