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. This is where the child_process module.
child_process module comes in; it allows Node.js applications to create child processes that can execute system commands, run other scripts or programs, and communicate with the parent process.
Why do we need child_process?
- Execute system commands: such as 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: such as calling Python or C++ programs
- Improve application performance: fully utilize multi-core CPUs through multiple processes
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.
Example
const
{
exec
}
=
require
(
'child_process'
)
;
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
}
`
)
;
}
}
)
;
Feature:
- Suitable for executing simple commands
- Returns the complete buffered output
- Has a maximum buffer limit (200KB by default)
2. execFile() - Execute an executable file
execFile() Similar to exec(), but executes the file directly rather than through a shell.
Example
const
{
execFile
}
=
require
(
'child_process'
)
;
execFile
(
'node'
,
[
'--version'
]
,
(
error
,
stdout
,
stderr
)
=>
{
if
(
error
)
{
throw
error
;
}
console.
log
(
stdout
)
;
}
)
;
Feature:
- compared to
exec()More secure (does not go through a shell) - More efficient execution
- Cannot use shell features (such as pipes, wildcards, etc.)
3. spawn() - Stream-process child processes
spawn() The method uses a streaming interface to handle the input and output of child processes.
Example
const
{
spawn
}
=
require
(
'child_process'
)
;
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
}
`
)
;
}
)
;
Feature:
- Suitable for handling large amounts of output
- Stream processing, memory efficient
- Can process output in real time
4. fork() - Create a Node.js child process
fork() Is spawn() is a special case of spawn(), used specifically for creating new Node.js processes.
Example
const
{
fork
}
=
require
(
'child_process'
)
;
const
child
=
fork
(
'child.js'
)
;
child.
on
(
'message'
,
(
msg
)
=>
{
console.
log
(
'Message from child process:'
,
msg
)
;
}
)
;
child.
send
(
{
hello
:
'world'
}
)
;
Feature:
- Create a new Node.js instance
- Built-in IPC (Inter-Process Communication) channel
- Suitable for CPU-intensive tasks
Inter-Process Communication (IPC)
The parent and child processes can communicate through the send() and message event.
Parent process (parent.js):
Example
const
{
fork
}
=
require
(
'child_process'
)
;
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
process.
on
(
'message'
,
(
msg
)
=>
{
console.
log
(
'Child process received:'
,
msg
)
;
process.
send
(
{
child
:
'Hello from child'
}
)
;
}
)
;
Error handling
It is very important to handle child process errors correctly:
Example
const
{
spawn
}
=
require
(
'child_process'
)
;
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
- Safety: avoid passing user input directly to child processes
- Resource management: promptly clean up completed child processes
- Error handling: always handle error events and exit events
- Performance considerations: for frequently created child processes, consider using a process pool
- Cross-platform compatibility: be aware of command differences across operating systems
Summary
child_process The module is the core module for handling child processes in Node.js, providing four methods for creating child processes:
exec()- suitable for simple commandsexecFile()- suitable for executing executable filesspawn()- suitable for stream processingfork()- suitable for creating Node.js child processes
By choosing the appropriate method based on specific needs and paying attention to error handling and resource management, you can fully leverage Node.js's multi-process capabilities.
Node.js Built-in Modules