child_process
Running shell commands and spawning processes from Node.js — exec, spawn, execFile, fork, and handling output.
What it is, in plain English: The child_process module lets Node.js spawn external processes. exec() runs a shell command and buffers the output — good for short commands. spawn() runs a command with streaming output — good for long-running processes. execFile() runs an executable directly (no shell — safer and faster). fork() spawns a new Node.js process and sets up message-passing between parent and child.
Running commands from Node.js
exec — run a shell command
import { exec } from "child_process";
import { promisify } from "util";
const execAsync = promisify(exec);
// Run a git command:
const { stdout, stderr } = await execAsync("git log --oneline -5");
console.log(stdout); // last 5 commits
// Check Node.js version:
const { stdout: version } = await execAsync("node --version");
console.log(version.trim()); // "v20.15.0"
// Handle errors:
try {
await execAsync("ls /nonexistent");
} catch (e) {
console.error("Command failed:", e.message);
console.error("Exit code:", e.code); // e.g. 2
console.error("Stderr:", e.stderr);
}spawn — streaming output for long commands
import { spawn } from "child_process";
// Good for: npm install, build tools, long-running processes
const install = spawn("npm", ["install"], {
cwd: "./my-project", // working directory
stdio: "pipe", // capture stdout/stderr (default)
});
install.stdout.on("data", (chunk) => process.stdout.write(chunk));
install.stderr.on("data", (chunk) => process.stderr.write(chunk));
install.on("close", (code) => {
if (code === 0) console.log("Install successful!");
else console.error(`Install failed with code ${code}`);
});
// Kill a process:
const proc = spawn("long-running-command");
setTimeout(() => proc.kill("SIGTERM"), 10000); // kill after 10s
Shell injection risk.
Never pass user input directly to
exec() — it goes through the shell.
Use execFile() or spawn() with an args array instead.
Try It Yourself
Official Sources
- Node.js Docs — child_process
- Node.js Docs — child_process.exec()
- Node.js Docs — child_process.spawn()
- execa — npm package
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.