Synchronous startup tasks
A short-lived trusted command must finish before subsequent initialization continues.
Node.js · Function
execSync executes a shell command and waits synchronously for the child process to close. It returns standard output or throws when execution times out or the command exits unsuccessfully.
execSync runs a command through a shell and does not return until the child process closes. It returns command output as a Buffer by default or as a string when an encoding is selected, and throws if execution times out or the process exits unsuccessfully.
execSync(command[, options])| Name | Type | Description |
|---|---|---|
command | string | Shell command to execute. |
options | Object | Optional child-process options, including timeout, killSignal, encoding, cwd, env, shell, input, and stdio settings. |
The command's standard output, as a Buffer by default or as a string when an encoding is specified; throws on timeout or non-zero exit status.
import { execSync } from "node:child_process";
const output = execSync("node -p '1 + 2'", { encoding: "utf8" });
console.log(output.trim());Runs a trusted command synchronously and converts its standard output to a string.
A short-lived trusted command must finish before subsequent initialization continues.
A local development or build script needs command output immediately.
A small administrative utility runs a fixed, trusted shell command.
execSync executes a shell command synchronously and waits for the child process to close. It blocks the event loop during that wait and returns the command's output, normally as a Buffer unless an encoding is configured.
Follow-up: Why might execFileSync be preferable? It avoids shell interpretation when invoking an executable directly, reducing shell-injection risk for argument-based execution.
A timeout causes the method to send the configured kill signal, but the call does not return until the process has completely exited. If the child handles SIGTERM and stays alive, the parent continues waiting.
Follow-up: What operational consequence follows? A timeout is not necessarily an immediate upper bound on the synchronous call's duration.
The function throws when the command times out or exits with a non-zero status. The thrown Error includes the result information from the synchronous spawn operation, which can be used when diagnosing the failure.
Follow-up: What alternative gives structured control over status and streams? spawnSync returns a result object rather than using shell command parsing and exception-based failure for non-zero status.
child_process.execchild_process.execFileSyncchild_process.spawnSyncchild_process.fork