In Node.js, you can create a child process by using the ‘child_process‘ module, which exposes several methods for spawning and managing child processes. Here’s an overview of the primary methods for creating child processes:
1. ‘spawn()‘: This method creates a new process, executing a given command with the provided arguments. It returns a ‘ChildProcess‘ instance and doesn’t block the event loop.
const { spawn } = require('child_process');
const child = spawn('command', ['arg1', 'arg2']);
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}`);
});
2. ‘exec()‘: This method creates a new process, running a given command in a shell, buffering its output. It is useful when you want to capture the command’s output. Like ‘spawn()‘, it also returns a ‘ChildProcess‘ instance.
const { exec } = require('child_process');
exec('command', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
3. ‘fork()‘: This method creates a new child process specifically for running a Node.js module. It implements a built-in communication channel between the parent and child processes. It returns a ‘ChildProcess‘ instance as well.
const { fork } = require('child_process');
const child = fork('./child_module.js');
child.on('message', (message) => {
console.log(`Parent received message: ${message}`);
});
child.send('Hello from parent');
Here is the code for ‘child_module.js‘:
process.on('message', (message) => {
console.log(`Child received message: ${message}`);
process.send('Hello from child');
});
4. ‘execFile()‘: Similar to ‘exec()‘, this method spawns a new process for an executable file or directly for a ‘.exe‘ file, with the specified arguments. It is a safer alternative to ‘exec()‘ when working with untrusted user input.
const { execFile } = require('child_process');
execFile('file.exe', ['arg1', 'arg2'], (error, stdout, stderr) => {
if (error) {
console.error(`execFile error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
In summary, you can create child processes in Node.js using the ‘child_process‘ module and its methods, such as ‘spawn()‘, ‘exec()‘, ‘fork()‘, and ‘execFile()‘. Each of these methods has its specific use cases and returns a ‘ChildProcess‘ instance that you can use to manage the generated child process.