Monday, July 29, 2019

What is Node.js 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:
  1. 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
  1. const exec = require('child_process').exec;  
  2. exec('my.bat', (err, stdout, stderr) => {  
  3.   if (err) {  
  4.     console.error(err);  
  5.     return;  
  6.   }  
  7.   console.log(stdout);  
  8. });  
Create a batch file named my.bat having the following code:
File: my.bat
  1. dir  
  2. mkdir child  
Open Node.js command prompt and run the following code:
  1. 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
  1. console.log("Child Process " + process.argv[2] + " executed." );  
File: master.js
  1. const fs = require('fs');  
  2. const child_process = require('child_process');  
  3. for(var i=0; i<3; i++) {  
  4.    var workerProcess = child_process.exec('node support.js '+i,  
  5.       function (error, stdout, stderr) {  
  6.          if (error) {  
  7.             console.log(error.stack);  
  8.             console.log('Error code: '+error.code);  
  9.             console.log('Signal received: '+error.signal);  
  10.          }  
  11.          console.log('stdout: ' + stdout);  
  12.          console.log('stderr: ' + stderr);  
  13.       });  
  14.       workerProcess.on('exit', function (code) {  
  15.       console.log('Child process exited with exit code '+code);  
  16.    });  
  17. }  
Open Node.js command prompt and run the following code:
  1. 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:
  1. 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
  1. console.log("Child Process " + process.argv[2] + " executed." );  
File: master.js
  1. const fs = require('fs');  
  2. const child_process = require('child_process');  
  3.  for(var i=0; i<3; i++) {  
  4.    var workerProcess = child_process.spawn('node', ['support.js', i]);  
  5.   workerProcess.stdout.on('data', function (data) {  
  6.       console.log('stdout: ' + data);  
  7.    });  
  8.  workerProcess.stderr.on('data', function (data) {  
  9.       console.log('stderr: ' + data);  
  10.    });  
  11.  workerProcess.on('close', function (code) {  
  12.       console.log('child process exited with code ' + code);  
  13.    });  
  14. }  
Open Node.js command prompt and run the following code:
  1. 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:
  1. 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
  1. const fs = require('fs');  
  2. const child_process = require('child_process');  
  3.  for(var i=0; i<3; i++) {  
  4.    var worker_process = child_process.fork("support.js", [i]);    
  5.   worker_process.on('close', function (code) {  
  6.       console.log('child process exited with code ' + code);  
  7.    });  
  8. }  
Open Node.js command prompt and run the following code:
  1. node master.js  
Node.js child process fork() example 1

No comments:

Post a Comment