Node.js child_process Module
Node.js is a single-threaded JavaScript runtime environment, but sometimes we need to execute system commands or run other programs. In such cases, we need to use thechild_processmodule.
child_processThe module allows Node.js applications to create child processes, which can execute system commands, run other scripts or programs, and communicate with the parent process.
Why do we need child_process?
- Execute system commands: For example, executing
ls、gitand other command-line tools - Run CPU-intensive tasks: Avoid blocking the Node.js main thread
- Interact with programs written in other languages: For example, calling Python or C++ programs
- Improve application performance: Fully utilize multi-core CPUs through multi-process
Four methods for creating child processes
1. exec() - Execute simple commands
exec()The method is used to execute simple shell commands and buffer the output results.
Example
exec('ls -l', (error, stdout, stderr) => {
if (error) {
console.error(`Execution error: ${error}`);
return;
}
console.log(`Standard output:\n${stdout}`);
if (stderr) {
console.error(`Standard error output:\n${stderr}`);
}
});
Features:
- Suitable for executing simple commands
- Returns the complete buffered output
- Has a maximum buffer limit (default 200KB)
2. execFile() - Execute executable files
execFile()Similar toexec(), but directly executes the file instead of going through the shell.
Example
execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
Features:
- Compare
exec()More secure (does not go through the shell) - Higher execution efficiency
- Cannot use shell features (such as pipes, wildcards, etc.)
3. spawn() - Stream processing of child processes
spawn()The method uses a streaming interface to handle the input/output of child processes.
Example
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`Standard output: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`Standard error output: ${data}`);
});
ls.on('close', (code) => {
console.log(`Child process exit code: ${code}`);
});
Features:
- Suitable for handling large amounts of output
- Streaming processing, high memory efficiency
- Can process output in real time
4. fork() - Create Node.js child processes
fork()Yesspawn()A special case of , specifically used to create new Node.js processes.
Example
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Message from child process:', msg);
});
child.send({ hello: 'world' });
Features:
- Creates a new Node.js instance
- Built-in IPC (inter-process communication) channel
- Suitable for CPU-intensive tasks
Inter-process communication (IPC)
Parent and child processes can communicate throughsend()andmessageevents.
Parent process (parent.js):
Example
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Parent process received:', msg);
});
child.send({ parent: 'Hello from parent' });
Child process (child.js):
Example
console.log('Child process received:', msg);
process.send({ child: 'Hello from child' });
});
Error handling
Properly handling child process errors is very important:
Example
const child = spawn('some_command');
child.on('error', (err) => {
console.error('Failed to start child process:', err);
});
child.stderr.on('data', (data) => {
console.error(`Child process error: ${data}`);
});
child.on('exit', (code, signal) => {
if (code) console.log(`Child process exit code: ${code}`);
if (signal) console.log(`Child process terminated by signal: ${signal}`);
});
Best practices
- Security: Avoid passing user input directly to child processes
- Resource management: Clean up completed child processes in a timely manner
- Error handling: Always handle error events and exit events
- Performance considerations: For frequently created child processes, consider using a process pool
- Cross-platform compatibility: Pay attention to command differences across different operating systems
Summary
child_processThe module is the core module in Node.js for handling child processes, providing four methods for creating child processes:
exec()- Suitable for simple commandsexecFile()- Suitable for executing executable filesspawn()- Suitable for streaming processingfork()- Suitable for creating Node.js child processes
Choose the appropriate method based on specific needs, and pay attention to error handling and resource management to fully leverage Node.js's multi-process capabilities.
Other extensions
Node.js built-in modules