In Node.js, child processes can be created to run external commands or scripts independently from the main process.
The "child_process" module provides the necessary functionalities for working with child processes.
spawn(): Launches a new process with the given command.
exec(): Executes a command in a shell and buffers the output.
execFile(): Similar to exec(), but executes a file directly instead of through a shell.
fork(): Used to spawn new Node.js processes.
The spawn function is used to spawn a new process and execute a command.
const { spawn } = require('child_process'); const childProcess = spawn('ls', ['-l', '-a']); childProcess.stdout.on('data', (data) => { console.log(`Child Process Output: ${data}`); }); childProcess.on('close', (code) => { console.log(`Child Process Exited with Code: ${code}`); });
The "exec" function is used to execute a command in a shell.
const { exec } = require('child_process'); exec('ls -l -a', (error, stdout, stderr) => { if (error) { console.error(`Error: ${error.message}`); return; } console.log(`Child Process Output: ${stdout}`); });
The `promisify` utility from the `util` module can be used to convert callback-based functions to promise-based functions.
const { promisify } = require('util'); const execAsync = promisify(require('child_process').exec); async function runCommand() { try { const { stdout } = await execAsync('ls -l -a'); console.log(`Child Process Output: ${stdout}`); } catch (error) { console.error(`Error: ${error.message}`); } } runCommand();
The "fork" function is used to spawn a new Node.js process, and communication between the parent and child processes can be achieved through inter-process communication (IPC).
create file with name "parent.js" and paste the below code
const { fork } = require('child_process'); const childProcess = fork('child.js'); childProcess.on('message', (message) => { console.log(`Parent received message: ${message}`); }); childProcess.send('Hello from parent!');
create file with name "child.js" and paste the below code.
process.on('message', (message) => { console.log(`Child received message: ${message}`); process.send('Hello from child!'); });
Run the code of parent process file: -> parent.js with command `node parent.js`
// terminal Console Output will be: > > node parent.js Child received message: Hello from parent! Parent received message: Hello from child!