Node.js Reference ยท child_process, worker_threads and cluster
Node.js child_process.exec() method
Reference for child_process.exec() in Node.js: run a shell command, get buffered stdout and stderr, handle non-zero exits, maxBuffer and timeouts, and avoid injection.
child_process.exec() runs a command string in a shell (/bin/sh on Unix, cmd.exe on Windows), waits for it to finish and gives you all of its output at once: a callback receives (error, stdout, stderr) as strings. It is the quickest way to run a one-line command, use pipes, redirects, globs or other shell syntax, and look at the result.
The convenience has costs. The whole output is held in memory and capped by maxBuffer, and the command string is interpreted by the shell, so building it from user input is dangerous. For a plain program with arguments use execFile(); for large or streaming output use spawn().
import { exec } from 'node:child_process'; exec('echo hello && echo world', (error, stdout, stderr) => { console.log(stdout); });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
child_process.exec(command: string, options?: object, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess
| Name | Description |
|---|---|
command |
The command line, interpreted by the shell. |
options.cwd |
Working directory. |
options.env |
Environment for the shell and the command. Default process.env. |
options.encoding |
Output encoding. Default 'utf8'; 'buffer' returns Buffers. |
options.shell |
The shell to use. Default /bin/sh (Unix) or process.env.ComSpec (Windows). |
options.timeout |
Kill the child after this many milliseconds. Default 0 (no limit). |
options.maxBuffer |
Largest allowed size of stdout or stderr in bytes. Default 1048576. |
options.killSignal |
Signal used for timeout, maxBuffer and abort. Default 'SIGTERM'. |
options.signal |
An AbortSignal to cancel the command. |
Returns: the ChildProcess, so you can still reach child.stdin or call child.kill(). With util.promisify(exec) the promise resolves to { stdout, stderr }, and the ChildProcess is available as promise.child.
Errors: the callback's error is null only on exit code 0. Otherwise it is an Error with code (the exit code, or a string such as ERR_CHILD_PROCESS_STDIO_MAXBUFFER or ENOENT), killed, signal, cmd, and in the callback and promise cases the collected stdout and stderr.
Usage notes
- Never insert untrusted text into the command string. A command such as
"ls " + userInputlets a visitor who sends; rm -rf ~run it. Use execFile() with an argument array, or validate strictly. See Shell injection. - Output beyond
maxBuffermakes Node kill the child and report an error, with the truncated text attached. Raise the limit or switch tospawn()for big output. - The shell, and therefore the syntax, depends on the platform. Scripts using
&&, pipes and$VARare not portable to Windowscmd.exe. timeoutkills the shell. A command it started may survive if the shell does not forward the signal, so preferexec-ing the final command (exec sleep 5) or useexecFile().- Both streams are decoded as UTF-8 by default; invalid sequences become replacement characters. Use
encoding: 'buffer'for binary data. - Stderr output does not mean failure. Many programs write warnings there and still exit 0.
- Starting a shell costs a few milliseconds more than starting the program directly.