Nodejs Child Process

Using multiple processes is the best way to scale a Node application. Node.js is designed for building distributed applications with many nodes. This is why it’s named Node. Scalability is baked into the platform and it’s not something you start thinking about later in the lifetime of an application.

In this article we look at how to create a basic child process which can be used to run long-running processes in the background.

Fork A Process

Let’s consider a process in which an array is iterated over and the data is acted upon. To do this basically we will be forking a child process with the in-built child_process module to send the data to a worker file.

var cp = require('child_process');
var child = cp.fork('./worker');
var obj = [1,2,3,4,5];
child.send(obj);

Child Process Worker (worker.js)

The worker file created as a fork is basically then run in background releasing the mail process allowing you to carry on with other functions.

Once the process is finished with the async function, the process can be killed with process.exit(0) call.

process.on('message', (obj) => {
    console.log(obj) //[1,2,3,4,5]
    obj.forEach((o)=>{
        //Do something with the data
    })
    process.exit(0) //Kill child process
})

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.