Child Process

The Node.js child process module provides the ability to spawn child processes in a similar manner to popen(3).

There are three major way to create child process:

  • child_process.exec() method: This method runs a command in a console and buffers the output.
  • child_process.spawn() method: This method launches a new process with a given command.
  • child_process.fork() method: This method is a special case of spawn() method to create child processes.

Node.js child_process.exec() method

The child_process.exec() method runs a command in a console and buffers the output.

Syntax:

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

Parameters:

1) command: It specifies the command to run, with space-separated arguments.

2) options: It may contain one or more of the following options:

  • cwd: It specifies the current working directory of the child process.
  • env: It specifies environment key-value pairs.
  • encoding: String (Default: 'utf8')
  • shell: It specifies string Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)
  • timeout: Number (Default: 0)
  • maxBuffer: Number (Default: 200*1024)
  • killSignal: String (Default: 'SIGTERM')
  • uid Number: Sets the user identity of the process.
  • gid Number: Sets the group identity of the process.

callback: The callback function specifies three arguments error, stdout and stderr which is called with the following output when process terminates.

Node.js child_process.exec() example 1

Let's see the simple process example to print architecture, pid, platform and version of the process.

File: child_process_example1.js

snippet
const exec = require('child_process').exec;
exec('my.bat', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

Create a batch file named my.bat having the following code:

File: my.bat

snippet
dir
mkdir child

Open Node.js command prompt and run the following code:

snippet
node child_process_example1.js

It will execute two commands dir and mkdir child. The dir command will display list of current directory and mkdir command will create a new directory. For linux, you can you ls command to display the current directory list.

Node.js child process example 1

It will create a new directory also.

Node.js child process example 2

Node.js child_process.exec() example 2

Create two js files named support.js and master.js, having the following code:

File: support.js

snippet
console.log("Child Process " + process.argv[2] + " executed." );

File: master.js

snippet
const fs = require('fs');
const child_process = require('child_process');
for(var i=0; i<3; i++) {
   var workerProcess = child_process.exec('node support.js '+i,
      function (error, stdout, stderr) {
         if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
         }
         console.log('stdout: ' + stdout);
         console.log('stderr: ' + stderr);
      });
      workerProcess.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
   });
}

Open Node.js command prompt and run the following code:

snippet
node master.js
Node.js child process exec() example 1

Node.js child_process.spawn() method

The child_process.spawn() method launches a new process with a given command. This method returns streams (stdout & stderr) and it is generally used when the process returns large amount of data.

Syntax:

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

Parameters:

1) command: It specifies the command to run.

2) args: It specifies an array List of string arguments.

3) options: It may contain one or more of the following options:

  • cwd: It specifies the current working directory of the child process.
  • env: It specifies environment key-value pairs.
  • stdio: Array|String Child's stdio configuration
  • customFds: Array Deprecated File descriptors for the child to use for stdio
  • detached Boolean : The child will be a process group leader
  • uid Number: Sets the user identity of the process.
  • gid Number: Sets the group identity of the process.

Node.js child_process.spawn() example

Create two js files named support.js and master.js, having the following code:

File: support.js

snippet
console.log("Child Process " + process.argv[2] + " executed." );

File: master.js

snippet
const fs = require('fs');
const child_process = require('child_process');
 for(var i=0; i<3; i++) {
   var workerProcess = child_process.spawn('node', ['support.js', i]);
  workerProcess.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
   });
 workerProcess.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
   });
 workerProcess.on('close', function (code) {
      console.log('child process exited with code ' + code);
   });
}

Open Node.js command prompt and run the following code:

snippet
node master.js
Node.js child process spawn() example 1

Node.js child_process.fork() method

The child_process.fork method is a special case of the spawn() to create Node processes. This method returns object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance.

Syntax:

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

Parameters:

1) modulePath: This is a string specifies the module to run in the child.

2) args: It specifies an array List of string arguments.

3) options: It may contain one or more of the following options:

  • cwd: It specifies the current working directory of the child process.
  • env: It specifies environment key-value pairs.
  • execPath: This is a string Executable used to create the child process.
  • execArgv: It specifies Array List of string arguments passed to the executable (Default: process.execArgv).
  • silent: It specifies Boolean If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false).
  • uid Number: Sets the user identity of the process.
  • gid Number: Sets the group identity of the process.

Node.js child_process.fork() example

Create two js files named support.js and master.js, having the following code:

File: support.js

snippet
const fs = require('fs');
const child_process = require('child_process');
 for(var i=0; i<3; i++) {
   var worker_process = child_process.fork("support.js", [i]);	
  worker_process.on('close', function (code) {
      console.log('child process exited with code ' + code);
   });
}

Open Node.js command prompt and run the following code:

snippet
node master.js
Node.js child process fork() example 1
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +