Node.js Child Process Error— exec, spawn, ENOENT Fixed [2026]
Also covers: exec vs spawn · capturing stderr · promisify · exit codes · large output streaming · env vars
⚡ Common Errors
Error: spawn git ENOENT ← command not found in PATH
Error: spawnSync /bin/sh ENOENT ← shell not found (Windows)
Error: stdout maxBuffer exceeded ← output too large for exec buffer✅ Choose the right API
// Short command, need complete output → exec (or promisified exec)
const { stdout } = await execAsync("git log --oneline -10")
// Long-running, large output, streaming → spawn
const child = spawn("npm", ["run", "build"])
child.stdout.pipe(process.stdout)exec vs spawn vs execFile — Which to Use
Node.js has three main child process APIs. exec runs through a shell, buffers all output, best for short commands. spawn runs the process directly, streams I/O, best for long-running processes. execFile runs a file directly without a shell, better security for known executables.
Fix ENOENT: Command Not Found
spawn ENOENT — command not in PATH or wrong nameimport { spawn, exec } from "child_process"
// ❌ ENOENT — 'git' not found (rare on Linux, common on Windows)
spawn("git", ["status"])
// ✅ Fix A — use shell: true (runs through system shell, resolves PATH)
spawn("git", ["status"], { shell: true })
// ✅ Fix B — provide full path to executable
spawn("/usr/bin/git", ["status"])
// ✅ Fix C — use exec (always uses shell)
exec("git status", (err, stdout) => {
if (err) console.error(err)
else console.log(stdout)
})
// Windows-specific — many commands have .cmd/.exe extension:
// ❌ spawn("npm", ["install"]) — fails on Windows (npm is npm.cmd)
// ✅ spawn("npm", ["install"], { shell: true }) — shell resolves npm.cmd
// Check if command exists before spawning:
import { execSync } from "child_process"
try {
execSync("git --version", { stdio: "ignore" })
console.log("git is available")
} catch {
console.error("git is not installed")
}Capture stdout and stderr Correctly
Output missing or only getting partial resultsimport { exec, spawn } from "child_process"
// --- exec — callback with stdout and stderr ---
exec("npm list --depth=0", { maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
console.error("Exit code:", error.code)
console.error("stderr:", stderr)
return
}
console.log("stdout:", stdout)
})
// --- spawn — event-based streaming ---
const child = spawn("npm", ["run", "build"])
let stdout = ""
let stderr = ""
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString()
process.stdout.write(chunk) // stream to parent stdout in real time
})
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString()
process.stderr.write(chunk) // stream stderr
})
child.on("close", (code) => {
console.log(`Process exited with code ${code}`)
if (code !== 0) {
console.error("Build failed:", stderr)
}
})Use promisify for async/await with exec
Callback-style exec in async code — convert to Promiseimport { exec } from "child_process"
import { promisify } from "util"
// ✅ Promisify exec for async/await
const execAsync = promisify(exec)
async function getGitLog(): Promise<string[]> {
const { stdout, stderr } = await execAsync("git log --oneline -20", {
maxBuffer: 1024 * 1024, // 1MB buffer
})
if (stderr) console.warn("git stderr:", stderr)
return stdout.trim().split("
").filter(Boolean)
}
// ✅ Node 15+ — import directly from child_process/promises
import { exec } from "node:child_process/promises"
async function runCommand(cmd: string) {
try {
const { stdout } = await exec(cmd)
return stdout.trim()
} catch (err: any) {
// err.code = exit code, err.stderr = error output
throw new Error(`Command failed (${err.code}): ${err.stderr}`)
}
}
// Usage:
const version = await runCommand("node --version")
console.log("Node version:", version) // v22.0.0Handle Non-Zero Exit Codes
Process exits with code 1 — treat as error and extract stderrimport { spawn } from "child_process"
function runScript(script: string): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const child = spawn("node", [script], {
env: { ...process.env }, // inherit parent environment
})
let stdout = ""
let stderr = ""
child.stdout.on("data", (d: Buffer) => { stdout += d.toString() })
child.stderr.on("data", (d: Buffer) => { stderr += d.toString() })
child.on("close", (code) => {
if (code === 0) {
resolve({ stdout, stderr })
} else {
reject(new Error(`Script exited with code ${code}\nstderr: ${stderr}`))
}
})
child.on("error", (err) => {
reject(err) // ENOENT, permission denied, etc.
})
})
}
// Usage:
try {
const { stdout } = await runScript("./scripts/migrate.js")
console.log("Migration output:", stdout)
} catch (err) {
console.error("Migration failed:", err.message)
process.exit(1)
}Stream Large Output with spawn
exec maxBuffer exceeded — output too largeimport { spawn } from "child_process"
import { createWriteStream } from "fs"
// ❌ exec maxBuffer exceeded for large output
// exec("git log --all", ...) → Error: stdout maxBuffer exceeded
// ✅ spawn — streams output without buffering limit
const logFile = createWriteStream("./git.log")
const child = spawn("git", ["log", "--all", "--format=%H %s"])
// Pipe stdout directly to a file
child.stdout.pipe(logFile)
child.on("close", (code) => {
logFile.close()
console.log(`Wrote git log with exit code ${code}`)
})
// ✅ Pass env variables to child process
const build = spawn("npm", ["run", "build"], {
env: {
...process.env, // ← inherit PATH and all parent vars
NODE_ENV: "production", // ← override or add specific vars
CI: "true",
},
stdio: "inherit", // ← child process shares parent's stdio (prints directly)
})
build.on("close", (code) => {
if (code !== 0) process.exit(code ?? 1)
})Use stdio: 'inherit' to connect the child process directly to the parent's stdin/stdout/stderr. This is the simplest way to show a subprocess's output in your terminal without piping events manually.
Prevention
- Use shell: true in spawn options on Windows or when the command relies on shell PATH resolution
- Use promisify(exec) or import from 'node:child_process/promises' for clean async/await patterns
- Always listen to the 'error' event on spawned processes — it fires for ENOENT and permission errors
- Check exit code AND stderr — exit code 0 with stderr content is common for warnings
- Set maxBuffer for exec when output may be larger than the default 200KB
- Use spawn with stdio: 'inherit' for build scripts that should display output in real time
- Always spread ...process.env when setting env — omitting it loses PATH and breaks most commands
Frequently Asked Questions
What is the difference between exec and spawn in Node.js?+−
Why do I get ENOENT when running a command with child_process?+−
How do I capture stderr from a child process?+−
Why does exec silently fail with no error?+−
How do I run a child process and wait for it to finish?+−
How do I pass environment variables to a child process?+−
Need Expert Help?
We Build Production Node.js Backends
Softplix engineers build Node.js APIs, CLI tools, and automation scripts with TypeScript, proper process management, and production-grade error handling. Let us help.
Talk to an Engineer