What does the child_process module do?
What child_process is
child_processis a built-in Node.js module that lets you create child processes from the current Node.js application.
In other words:
It lets you run other programs, scripts, or OS commands, as if you'd typed them into a terminal.
1. Why child_process is needed
It lets you:
- run system commands (
ls,ping,git,python,ffmpeg, and so on); - launch other Node.js scripts as separate processes;
- run computation in parallel;
- bridge different languages and tools (for example, Node.js ↔ Python);
- build CLI tools and pipelines (UNIX-style).
2. The main methods of child_process
| Method | Returns | Description |
|---|---|---|
exec() | a process object (ChildProcess) | Runs a command in a shell and buffers the result |
execFile() | a process object | Runs an executable directly (no shell) |
spawn() | a process object | Creates a streaming process, handy for large data |
fork() | a process object | Launches a new Node.js process (with a built-in IPC channel) |
3. Examples of each method
1) exec(): run a command and get the result
javascript
const { exec } = require('child_process');
exec('ls -la', (error, stdout, stderr) => {
if (error) console.error(`Error: ${error.message}`);
if (stderr) console.error(`STDERR: ${stderr}`);
console.log(`Result:\n${stdout}`);
});Good for:
- simple commands;
- getting a finished result as text;
- small amounts of output.
But! exec() buffers all output in memory,
so for large data spawn() is a better fit.
2) spawn(): a streaming process launch
javascript
const { spawn } = require('child_process');
const child = spawn('ping', ['google.com']);
child.stdout.on('data', (data) => {
console.log(`Output: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`Error: ${data}`);
});
child.on('close', (code) => {
console.log(`Process exited with code ${code}`);
});Good for:
- long-running processes (for example,
ffmpeg,npm run,curl); - processing data in real time (through
stdout,stderr).
3) execFile(): run a specific file
javascript
const { execFile } = require('child_process');
execFile('node', ['-v'], (error, stdout) => {
if (error) throw error;
console.log(`Node.js version: ${stdout}`);
});The difference from exec():
- doesn't use a shell (
bash,cmd); - faster and safer (less risk of command injection);
- a great fit for calling executables or scripts.
4) fork(): launch a new Node.js process
javascript
const { fork } = require('child_process');
const child = fork('worker.js');
child.on('message', (msg) => console.log('Response from the worker:', msg));
child.send({ task: 'compute', value: 5 });worker.js
javascript
process.on('message', (msg) => {
const result = msg.value * 2;
process.send({ result });
});Features of fork():
- used only for Node.js files;
- creates a separate Node.js process;
- supports a built-in message channel (IPC);
- great for parallel computation and modular architecture.
4. Events on the ChildProcess object
| Event | Description |
|---|---|
exit | The process has finished |
close | All I/O streams have been closed |
error | An error happened at launch |
message | A message was received (for fork()) |
disconnect | The IPC channel was closed |
5. Comparing the methods
| Method | Uses a shell | Returns the result | Streaming I/O | Typical task |
|---|---|---|---|---|
exec | Yes | As a string (stdout) | No | Simple commands |
execFile | No | As a string (stdout) | No | Running executables |
spawn | No | Streams (stdout, stderr) | Yes | Streaming work |
fork | No | Via IPC messages | Yes | Launching Node.js workers |
6. Where it's used in practice
Real-world scenarios:
- running Python or Go programs from Node.js;
- building custom CLI commands;
- image processing via
ImageMagick,ffmpeg,sharp; - integrating with
git,docker,kubectl; - distributing computation across several processes;
- running cron jobs.
7. Worth remembering
- Every process has its own memory and event loop.
- Data exchange between processes happens via IPC (Inter-Process Communication).
exec()can hang if its buffer overflows (1 MB by default).- For many parallel tasks, worker_threads is usually better (lighter than processes).
- PM2 or clustering (
cluster) is often used to manage many processes.
Summary
| Criterion | child_process |
|---|---|
| Purpose | Launching external programs and processes |
| API type | Asynchronous (callbacks or events) |
| Methods | exec, execFile, spawn, fork |
| Stream support | Via stdout / stderr |
| Data exchange | Via messages (IPC) or I/O |
| Use it for | Integrating with external commands, parallel computation, automation |
Conclusion:
The
child_processmodule makes Node.js an "orchestrator", it can launch any program, manage it, pass it data and get results back.It's the foundation for CLI tools, DevOps scripts, build systems and distributed computation.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.