Invoke external tools
Run a compiler, formatter, or operating-system utility while streaming its output.
Node.js · Module
The node:child_process module launches external commands and Node.js subprocesses. It offers asynchronous and synchronous APIs, stream-based process control, shell command execution, and IPC for forked Node.js processes.
The module starts external commands or additional Node.js processes. Asynchronous functions return ChildProcess event emitters, while synchronous variants wait for completion and block the event loop; spawned processes can communicate through standard streams, and forked Node.js processes can use IPC.
import { spawn, spawnSync, exec, execFile, fork } from 'node:child_process';
spawn(command[, args][, options])| Name | Type | Description |
|---|---|---|
command | string | The executable command to start. |
args | string[] | Command-line arguments passed to the executable. |
options | Object | Optional spawn configuration, including standard I/O and environment settings. |
Asynchronous process-creation methods return a ChildProcess instance; synchronous variants return the completed operation's result or throw on failure.
import { spawn } from 'node:child_process';
const child = spawn(process.execPath, ['-e', 'console.log("hello")']);
child.stdout.on('data', (chunk) => {
process.stdout.write(chunk);
});
child.on('close', (code, signal) => {
console.log(`closed: code=${code}, signal=${signal ?? 'none'}`);
});Starts a separate Node.js process asynchronously, reads its standard output, and reports how it ended.
Run a compiler, formatter, or operating-system utility while streaming its output.
Launch independent work without blocking the Node.js event loop.
Start another Node.js module and exchange messages with it.
Run a shell command and receive collected output on completion.
spawn starts a command asynchronously and returns a ChildProcess event emitter. Its arguments are supplied separately as a command and an argument array, and its standard streams can be consumed incrementally.
Follow-up: When would exec be preferable? Use it for a shell command when buffered stdout and stderr plus a completion callback are convenient, while recognizing the shell and input-safety implications.
exec starts a shell and runs a command inside it, then can invoke a callback when the process finishes. execFile invokes the executable directly rather than first starting a shell.
Follow-up: Why choose execFile for user-derived values? Keep values in separate argument positions and avoid shell parsing, reducing shell-injection exposure.
fork is a specialized form of spawn for launching another Node.js process. It establishes an IPC channel so the parent and child can exchange messages.
Follow-up: What trade-off does fork have? It is intended for Node.js modules and IPC, whereas spawn is the general mechanism for arbitrary executables.
ChildProcessspawnSync()exec()execFile()execSync()execFileSync()fork()