Node.js Child Process - GeeksforGeeks

10 Jul, 2020
Node.js is a web development framework that offers a variety of modules to work with. Usually, Node.js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.
The following are the four different ways to create a child process in Node.js:
spawn() method
fork() method
exec() method
execFile() method
Above mentioned ways are explained below:
spawn() method: This method spawns a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child object directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close and message.Syntax:
child_process.spawn(command[, args][, options])
Parameters:
command: Accepts a string which is the command to run.
args: List of string arguments. Default value is an empty array.
options:shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process.Additional options such as cwd, env, argv0, stdio etc can be used as per requirement.
shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process.
Additional options such as cwd, env, argv0, stdio etc can be used as per requirement.
Return Value: Returns a ChildProcess object.
Example:
const { spawn } = require('child_process');const child = spawn('dir', ['D:\Test'], {shell: true});child.stdout.on('data', (data) => {  console.log(`stdout: ${data}`);});  child.stderr.on('data', (data) => {  console.error(`stderr: ${data}`);});  child.on('close', (code) => {  console.log(`child process exited with code ${code}`);});
Output:
fork() method: The child_process.fork() is a special case of child_process.spawn() where the parent and the child process can communicate with each other via send(). The fork() allows separation of computation-intensive tasks from the main event loop. Child processes are independent of the parent except the IPC communication channel established between them. Each process has its own memory, therefore invoking a large number of child processes can affect the performance of the application. The shell option is not supported by child_process.fork().
Syntax:
child_process.fork(modulePath[, args][, options])
Parameters:
modulePath: Accepts a string that specifies the module to run in the child.
args: List of string arguments.
options: cwd, detached, env, execPath, execArgv are some of the available options for this method.
Return Value: Returns a ChildProcess instance.
Example: Filename: fork.js
// Write Javascript code herevar cp = require('child_process');  var child = cp.fork(__dirname + '/sub.js');  child.on('message', function(m) {  console.log('Parent process received:', m);});  child.send({ hello: 'from parent process' });  child.on('close', (code) => {  console.log(`child process exited with code ${code}`);});
Filename: sub.js
process.on('message', function(m) {  console.log('Child process received:', m);});  process.send({ hello: 'from child process' });
Output:
exec() method: This method creates a shell first and then executes the command.
Syntax:
child_process.exec(command[, options][, callback])
Parameters:
command: Accepts a string that specifies the command to run with space-separated arguments.
options: Some of the options available are cwd, env, encoding, shell, timeout etc
callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively.
Return Value: Returns an instance of ChildProcess.
Example:
const { exec } = require('child_process');  // Counts the number of directory in // current working directoryexec('dir | find /c /v ""', (error, stdout, stderr) => {  if (error) {    console.error(`exec error: ${error}`);    return;  }  console.log(`stdout: No. of directories = ${stdout}`);  if (stderr!= "")  console.error(`stderr: ${stderr}`);});
Output:
execFile() method: The child_process.execFile() function is does not spawn a shell by default. It is slightly more efficient than child_process.exec() as the specified executable file is spawned directly as a new process.
Syntax:
child_process.execFile(file[, args][, options][, callback])
Parameters:
file: Accepts a string that specifies the name or path of the file to run.
args: List of string arguments.
options: Some of the options available are cwd, env, encoding, shell, timeout etc
callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively.
Return Value: Returns an instance of ChildProcess.
Example:
const { execFile } = require('child_process');  // Executes the exec.js fileconst child = execFile('node', ['exec.js'],         (error, stdout, stderr) => {  if (error) {    throw error;  }  console.log(stdout);});
Output:
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Express.js express.Router() Function
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript