The
child_process module is stable and provides the ability to spawn subprocesses similar to popen(3).Overview
Thenode:child_process module enables spawning child processes to run shell commands, execute files, and create new Node.js processes.
Key Functions
Four main methods for creating child processes:| Method | Use Case | Spawns Shell |
|---|---|---|
spawn() | Streaming I/O, long-running processes | Optional |
exec() | Buffered output, shell commands | Yes |
execFile() | Buffered output, direct execution | No (default) |
fork() | New Node.js processes with IPC | No |
Asynchronous Methods
spawn(command[, args][, options])
Spawns a new process with streaming I/O.The command to run
List of string arguments
Configuration options
Current working directory. Default:
process.cwd()Environment key-value pairs. Default:
process.envExplicitly set
argv[0] sent to child processChild’s stdio configuration. Default:
'pipe'Prepare child to run independently of parent
Sets the user identity of the process
Sets the group identity of the process
Run command in a shell. Uses
/bin/sh on Unix, process.env.ComSpec on WindowsHide subprocess console window on Windows
AbortSignal to kill the child process
Maximum time in milliseconds the process is allowed to run
Signal to use when killing the process
ChildProcess instance
exec(command[, options][, callback])
Spawns a shell and executes a command, buffering output.The command to run, with space-separated arguments
Configuration options (extends spawn options)
Character encoding for stdout/stderr
Maximum execution time in milliseconds
Largest amount of data in bytes allowed on stdout or stderr
Signal to send when timeout is exceeded
Shell to execute the command with. Default:
/bin/sh on Unix, process.env.ComSpec on WindowsCalled when process terminates
errorstdoutstderr
ChildProcess instance
Promisified Version
execFile(file[, args][, options][, callback])
Similar toexec() but doesn’t spawn a shell by default (more efficient).
The name or path of the executable file to run
List of string arguments
Same as exec() options, plus:
No quoting or escaping of arguments on Windows
ChildProcess instance
fork(modulePath[, args][, options])
Special case ofspawn() for spawning new Node.js processes with IPC channel.
The module to run in the child
List of string arguments
Configuration options
Current working directory
Prepare child to run independently
Environment key-value pairs. Default:
process.envExecutable used to create the child process
List of string arguments passed to the executable. Default:
process.execArgvSerialization type for messages:
'json' or 'advanced'If
true, stdin, stdout, and stderr are piped to the parentChild’s stdio configuration. Must contain exactly one
'ipc' itemMaximum execution time in milliseconds
ChildProcess instance with additional communication channel
Synchronous Methods
spawnSync(command[, args][, options])
Object with
pid, output, stdout, stderr, status, signal, errorexecSync(command[, options])
The stdout from the command
execFileSync(file[, args][, options])
The stdout from the command
ChildProcess Class
Instances ofChildProcess represent spawned child processes.
Events
Event: ‘close’
Exit code if the child exited on its own
Signal that terminated the child process
Event: ‘disconnect’
Emitted after callingsubprocess.disconnect() or process.disconnect() in the child.
Event: ‘error’
- Process couldn’t be spawned
- Process couldn’t be killed
- Sending a message failed
Event: ‘exit’
Exit code
Signal that terminated the process
Event: ‘message’
Parsed JSON object or primitive value
net.Socket or net.Server objectprocess.send().
Event: ‘spawn’
Emitted once the child process has spawned successfully.Properties
subprocess.channel
Pipe representing the IPC channel to the child
subprocess.connected
true until subprocess.disconnect() is calledsubprocess.exitCode
Exit code of the child process, or
null if still runningsubprocess.killed
true after subprocess.kill() successfully sends a signalsubprocess.pid
Process identifier (PID) of the child process
subprocess.signalCode
Signal that terminated the child process
subprocess.spawnargs
Full list of command-line arguments the child process was spawned with
subprocess.spawnfile
Executable file name of the child process
subprocess.stdin, stdout, stderr
Writable stream representing the child’s stdin
Readable stream representing the child’s stdout
Readable stream representing the child’s stderr
Methods
subprocess.disconnect()
Closes the IPC channel between parent and child.subprocess.kill([signal])
Sends a signal to the child process.Signal to send
true if kill succeededsubprocess.ref()
Callingref() on a child process prevents the parent from exiting if the child is the only thing keeping it running.
subprocess.unref()
Callingunref() on a child process allows the parent to exit independently.
subprocess.send(message[, sendHandle][, options][, callback])
Sends a message to the child process when an IPC channel exists.Message to send
net.Socket or net.Server objectOptions object
Value used when passing
net.Socket instancesInvoked after the message is sent
true if the message was sentstdio Configuration
Thestdio option configures pipes between parent and child.
Shorthand Values
'pipe'-['pipe', 'pipe', 'pipe'](default)'overlapped'-['overlapped', 'overlapped', 'overlapped']'ignore'-['ignore', 'ignore', 'ignore']'inherit'-['inherit', 'inherit', 'inherit']or[0, 1, 2]
Array Values
Each index corresponds to an fd in the child (0=stdin, 1=stdout, 2=stderr):'pipe'- Create a pipe between child and parent'overlapped'- Same as'pipe'withFILE_FLAG_OVERLAPPEDon Windows'ipc'- Create an IPC channel for message passing'ignore'- Ignore the fd (opens/dev/null)'inherit'- Pass through the corresponding stdio stream- - Share a readable or writable stream
- - Share a file descriptor
null/undefined- Use default value
Detached Processes
On Windows
Settingdetached: true makes the child process continue running after the parent exits. The child gets its own console window.
On Unix
The child becomes the leader of a new process group and session. May continue running after parent exits regardless ofdetached.
Complete Examples
Piping Between Processes
IPC Between Parent and Child
Security Considerations
Best Practices
Choose the Right Method
spawn()- Streaming I/O, long-running processesexec()- Small output, shell commandsexecFile()- Small output, direct execution (more secure)fork()- Node.js processes with IPC
Handle Errors ProperlyAlways listen for
'error' events. Child processes can fail to spawn or be killed unexpectedly.