Run a bounded shell command
A backend needs to invoke a short, trusted system command and process its completed output.
Node.js · Function
Runs a command through a shell and buffers its stdout and stderr until completion. It reports results through a callback or, when promisified, a Promise.
exec() starts a shell, runs the supplied command, and buffers its standard output and standard error until completion. The callback receives an error when execution fails, plus stdout and stderr as strings by default; the returned ChildProcess can be used for process control.
child_process.exec(command[, options][, callback])| Name | Type | Description |
|---|---|---|
command | string | Command string to execute inside the shell. |
options | Object | Optional settings controlling execution, including encoding and other child-process behavior. |
callback | Function | Optional function called when the process terminates with error, stdout, and stderr. |
ChildProcess; the promisified form returns a Promise resolving to an object with stdout and stderr.
import { exec } from 'node:child_process';
exec('node -e "console.log(42)"', (error, stdout, stderr) => {
if (error) {
console.error(stderr || error.message);
return;
}
console.log(stdout.trim());
});Runs a fixed command through the shell and prints its standard output, or reports the failure.
A backend needs to invoke a short, trusted system command and process its completed output.
Application code prefers async/await over callback-style completion handling.
A command’s output must be captured and decoded with a selected character encoding.
exec() launches a shell and executes one command string, buffering stdout and stderr until the process completes. Its callback receives an error, stdout, and stderr, and the method returns a ChildProcess.
Follow-up: When should spawn() be preferred? Prefer it when shell interpretation is unnecessary or when streaming large output is important, because exec() buffers output.
The command is sent directly to a shell, so shell syntax and metacharacters are interpreted. A command assembled from untrusted input can therefore cause unintended execution.
Follow-up: How can shell risk be reduced? Avoid interpolating untrusted values and use an API that accepts an executable and argument array when shell semantics are not required.
The callback receives strings by default because Node.js decodes output as UTF-8. The encoding option controls decoding; using 'buffer' or an unrecognized encoding makes stdout and stderr Buffers.
Follow-up: What does util.promisify(exec) return? It returns a Promise for an object with stdout and stderr, while failures reject with the execution error.
child_process.execFile()child_process.spawn()child_process.fork()child_process.execFileSync()ChildProcess