Node.jschild_processError Fix2026 Updated

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

January 20266 min readNode.js 18/20/22 · TypeScript

⚡ Common Errors

Error
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

exec vs spawn — quick selection guide
// 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.

1

Fix ENOENT: Command Not Found

spawn ENOENT — command not in PATH or wrong name
3 min
ENOENT fixes
import { 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")
}
2

Capture stdout and stderr Correctly

Output missing or only getting partial results
3 min
Capture output from exec and spawn
import { 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)
  }
})
3

Use promisify for async/await with exec

Callback-style exec in async code — convert to Promise
2 min
promisify exec — async/await pattern
import { 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.0
4

Handle Non-Zero Exit Codes

Process exits with code 1 — treat as error and extract stderr
3 min
Exit code handling
import { 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)
}
5

Stream Large Output with spawn

exec maxBuffer exceeded — output too large
3 min
spawn for large output and piping
import { 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

Frequently Asked Questions

What is the difference between exec and spawn in Node.js?+
exec runs a command through a shell, buffers all output, and returns it in a callback when the process exits — best for short commands where you need the complete output. spawn starts the process directly (no shell by default), streams stdout/stderr as they arrive — best for long-running processes or large output. execFile is like exec but runs a file directly without a shell.
Why do I get ENOENT when running a command with child_process?+
ENOENT means the command was not found. With spawn, the command must be in the system PATH or you must provide the full path. On Windows, many commands (like git, npm) have .cmd or .exe extensions — use spawn('git', args, { shell: true }) or execFile to handle this. Also check that the required tool is installed on the machine.
How do I capture stderr from a child process?+
With exec, stderr is passed as the third argument in the callback: exec(cmd, (error, stdout, stderr) => {}). With spawn, listen to the stderr data event: child.stderr.on('data', (chunk) => {}). An exit code of 1 does not always mean error — check both exit code and stderr content.
Why does exec silently fail with no error?+
exec buffers output up to a limit (default 200KB). If the command output exceeds maxBuffer, exec silently kills the process and returns an error with code 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'. Increase maxBuffer: exec(cmd, { maxBuffer: 10 * 1024 * 1024 }) or switch to spawn for large output.
How do I run a child process and wait for it to finish?+
Use util.promisify(exec) to get a Promise-based version. Then await it: const { stdout } = await execAsync('npm list'). Alternatively, use the child_process/promises submodule in Node 15+: import { exec } from 'node:child_process/promises'.
How do I pass environment variables to a child process?+
Pass env in the options object. To inherit parent env and add extras: spawn('npm', ['start'], { env: { ...process.env, MY_VAR: 'value' } }). Without spreading process.env, the child process only gets the variables you explicitly set and loses PATH and all other parent environment variables.

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