Node.js Child Process

As we know that Node.js works on a single thread mechanism in which the events in the loop will be executed one by one but in some cases, the single thread mechanism can support a limited amount of load at a time.

 

While node.js is based on a single-threaded mechanism, but it does not mean that we cannot get the advantages of multiple processes at a time, for that there is a module called child process which is named child_process. In node.js, the child_process module will provide the ability to spawn the child processes in an asynchronous manner.

 

To access and implement asynchronous programming in node.js, the following are the different type of child process methods which are available in node.js.

 

Node.js Child Process Spawn Method

In node.js, the child process spawn() method is useful to launch a new process asynchronously for the given command without blocking the node.js event loop.

Following is the syntax of defining the child process spawn() method in node.js.

 

child_process.spawn(command[, args][, options]) 

Here, the command is used to define the required command to run, args is used to define the list of string arguments and options parameter is used to send required options like cwd, env, uid, gid, etc. based on our requirements.

 

In node.js, the child_process.spawn() method will spawn a new process using the given command, with command line arguments in args. If omitted, args defaults to an empty array.

Node.js Child Process Spawn Example

Following is the example of executing the multiple commands using spawn method in child_process module. Now, create two files named child.js and childprocess.js and paste the following code.

child.js

console.log("Spawn Method Example")

console.log("Child Process: " + process.argv[1] + " now executed." );

childprocess.js

const childProcess = require('child_process');

var process = childProcess.spawn('node', ['child.js']);

 

process.stdout.on('data', function (data) {

    console.log('stdout: ' + data);

});

 

process.stderr.on('data', function (data) {

    console.log('stderr: ' + data);

});

 

process.on('close', function (code) {

    console.log('Child process exit with code: ' + code);

});

console.log('Child Process');

If you observe the above code, we imported a child_process module by using the require directive and invoking another process with the spawn() method by sending required commands & arguments to perform multiple processes asynchronously.

 

When we execute the above example in node.js command prompt, we will get the result like as shown below.

 

Node.js Spawn() Method Example Result

 

If you observe the above result, when we invoke childprocess.js file in node.js command prompt, the child process object (process) has invoked other processes simultaneously.

Node.js Child Process Fork Method

In node.js, the child process fork() method will spawn a new process and it will invoke a specified module with a built-in communication channel that allows sending messages between parent and child.

 

Following is the syntax of defining the child process fork() method in node.js.

 

child_process.fork(modulePath[, args][, options]) 

Here, the modulePath is used to define the module to run in the child, args is used to define the list of string arguments and options parameter is used to send required options like cwd, env, uid, gid, etc. based on our requirements.

 

In node.js, the child_process.fork() method will spawn a new process using the given modulePath, with command line arguments in args. If omitted, args defaults to an empty array.

Node.js Child Process Fork Example

Following is the example of executing the multiple commands using the fork method in child_process module. Now, create two files named child.js and parent.js and paste the following code.

child.js

process.on('message', (msg) => {

    console.log('Message from the parent process :', msg);

});

 

let counter = 0;

for(var i = 0; i<4; i++){

            process.send({ counter: counter++ });

}

parent.js

const { fork } = require('child_process');

const forkedFile = fork('child.js');

 

forkedFile.on('message', (msg) => {

    console.log('Message from the child process :', msg);

});

 

forkedFile.send({ From : 'Tutlane.com' });

If you observe the above code, we imported a child_process module by using the require directive and invoking other childprocess with fork() method by sending the required module path. The childprocess will have an additional built-in communication channel to allow messages to be passed back and forth between parent and child.

 

When we execute the above example in node.js command prompt, we will get the result like as shown below.

 

Node.js Child Process Fork Method Example Result

 

If you observe the above result, when we invoke parent.js file in node.js command prompt, the child process object (forkedFile) has invoked other processes simultaneously.

Node.js Child Process Exec Method

In node.js, the child process exec() method will spawn a shell and execute the commands within that shell, passing the result using stdout and stderror to a callback function once the command execution complete.

 

Following is the syntax of defining the child process exec() method in node.js.

 

child_process.exec(command[, options][, callback])

Here, the command is used to define the required commands to run, options are used to send required options like cwd, env, uid, gid, etc. and the callback is used to specify the callback function with error, stdout and stderr parameters and it is called with the output once the process terminates.

 

In node.js, the child_process.exec() method will execute the commands in console using the given command, with command-line options. If omitted, options defaults to an empty array.

Node.js Child Process Exec Example

Following is the example of executing the commands using exec method in child_process module. Now, create a file called child.js and paste the following code.

child.js

var exec = require('child_process').exec;

exec('node -v', function(error, stdout, stderr) {

if(error){

throw error;

}

console.log('Stdout output : ' + stdout);

});

If you observe above code, we imported a child_process module by using require directive and executing “node -v” command with exec() method. The exec() method will return the result to callback function by using error, stdout and stderr parameters.

 

When we execute the above example in node.js command prompt, we will get the result like as shown below.

 

Node.js Child Process Exec Method Example Result

 

If you observe the above result, the exec() method has executed the given command and sent the result to callback function using the stdout parameter.

Node.js Child Process ExecFile Method

In node.js, the child process execFile() method is same as the exec() method but the only difference is the execFile() method will execute the command directly without spawning a shell by default.

 

Following is the syntax of defining the child process execFile() method in node.js.

 

child_process.execFile(file[, args][, options][, callback])

Here, the file is used to define the name or path of the executable file to run, args is used to send the list of string arguments, options are used to send required options like cwd, env, uid, gid, etc. and callback is used to specify the callback function with error, stdout and stderr parameters to send the child process output and it is called with the output once the process terminates.

 

In node.js, the child_process.execFile() method will execute the commands in console same as child_process.exec() method except that it does not spawn a shell by default. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than the chile_process.exec() method.

Node.js Child Process ExecFile Example

Following is the example of executing the commands using execFile method in child_process module. Now, create a file called child.js and paste the following code.

child.js

const { execFile } = require('child_process');

const childProcess = execFile('node', ['--version'], (error, stdout, stderr) => {

  if (error) {

    throw error;

  }

console.log("Stdout output :" ,stdout);

});

If you observe the above code, we imported a child_process module by using the require directive and executing the required commands with execFile() method. The execFile() method will return the result to callback function by using error, stdout and stderr parameters.

 

When we execute the above example in node.js command prompt, we will get the result like as shown below.

 

Node.js Child Process ExecFile Method Example Result

 

This is how we can achieve asynchronous programming in node.js with child process methods based on our requirements.