5 min read
•Question 50 of 62hardWhat is the Child Process module in Node.js?
Spawning and managing child processes.
What You'll Learn
- Creating child processes
- Different spawn methods
- Communication between processes
Child Process Methods
| Method | Description |
|---|---|
| spawn | Launches a new process with streaming I/O |
| exec | Spawns shell, buffers output |
| execFile | Like exec but without shell |
| fork | Spawns Node.js process with IPC |
spawn()
code.jsJavaScript
const { spawn } = require('child_process');
const ls = spawn('ls', ['-la']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});exec()
code.jsJavaScript
const { exec } = require('child_process');
exec('ls -la', (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error.message}`);
return;
}
console.log(`stdout: ${stdout}`);
});
// With promises
const util = require('util');
const execPromise = util.promisify(exec);
const { stdout } = await execPromise('ls -la');fork() - IPC Communication
code.jsJavaScript
// parent.js
const { fork } = require('child_process');
const child = fork('child.js');
child.send({ hello: 'world' });
child.on('message', (msg) => {
console.log('From child:', msg);
});
// child.js
process.on('message', (msg) => {
console.log('From parent:', msg);
process.send({ reply: 'got it' });
});