skip to content

In Node.js, after starting a program with child_process.spawn, how do you read its output, get its exit code, and detect that it never started?

level: juniorimportance: should knowfreq 50%

answer

  1. an EventEmitter comes back
  2. stdout and stderr are Readable streams
  3. close waits for stdio too
  4. missing program: an event, not a code

basics

~10 s

child_process.spawn returns a ChildProcess: read subprocess.stdout and subprocess.stderr as streams, take the exit code from the 'close' event, and listen for 'error', which fires with ENOENT when the program cannot be started.

solid answer

~40 s

`spawn()` returns a `ChildProcess`, an `EventEmitter` whose `stdout` and `stderr` are `Readable` streams; with the default `stdio: 'pipe'` you consume them with `'data'` listeners, `for await...of`, or by piping them somewhere. Chunks arrive as `Buffer`s unless you call `setEncoding()`. The result comes from `'close'`, called with `(code, signal)` once the process has ended *and* its stdio streams have closed; `'exit'` can fire while output is still in flight. Exactly one of `code` and `signal` is non-null, so a child killed by a signal reports `code === null`. A program that never starts (a missing binary, a missing `cwd`) has no exit code at all: Node emits `'error'` with `err.code === 'ENOENT'`. An `'error'` event with no listener is thrown, so one typo in a command name can crash the whole service.

code

javascript · 18 lines
javascript
import { spawn } from 'node:child_process';
import { once } from 'node:events';

const child = spawn(process.execPath, ['-e', 'console.log("converted"); process.exit(3)']);

let output = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
  output += chunk;
});

try {
  const [code, signal] = await once(child, 'close');
  console.log({ output: output.trim(), code, signal });
  // { output: 'converted', code: 3, signal: null }
} catch (err) {
  console.error(`could not start: ${err.code}`); // e.g. ENOENT
}

go deeper

for a junior

Recall that spawn returns a ChildProcess with stdout and stderr streams, that 'close' carries the exit code and signal, and that a missing program arrives as an 'error' event.

for a middle

Explain why 'close' waits for the stdio streams while 'exit' does not, why chunks are Buffers, and why an unread pipe can stall the child.

for a senior

Show you guard every child against a missing binary on a new host, since an unhandled 'error' event crashes the parent, and that you check code and signal separately.

for a principal

Treat external binaries as dependencies a service must verify at start-up and report clearly, rather than failures discovered on the first request after a deploy.

## What spawn gives back `child_process.spawn(command, args, options)` starts a program **asynchronously** and returns at once with a **`ChildProcess`** object. The program runs in its own operating-system process; the object is the parent's handle on it. `ChildProcess` extends **`EventEmitter`**, so everything you learn about the child arrives as events, and its standard streams are exposed as Node streams: - `subprocess.stdout` and `subprocess.stderr` are **`Readable`** streams carrying what the child writes. - `subprocess.stdin` is a **`Writable`** stream; a child that reads all of its input will not continue until you call `end()` on it. - `subprocess.pid` is the operating-system process ID, or `undefined` if the program could not be started. These three streams exist because the default is `stdio: 'pipe'`, which is shorthand for `['pipe', 'pipe', 'pipe']`. Set a position to `'inherit'` to share the parent's terminal, or `'ignore'` to attach `/dev/null`; the matching property is then `null`. ## Reading the output Output arrives in **chunks**, not lines and not one final string: - A `'data'` listener receives each chunk as a `Buffer`. Call `subprocess.stdout.setEncoding('utf8')` to receive strings, which also keeps a multibyte character split across two chunks intact. - `for await (const chunk of subprocess.stdout)` reads the same chunks with async iteration. - Piping the stream to a file or an HTTP response passes the data through without collecting it. Always consume a pipe you asked for. The pipes have a **limited, platform-specific capacity**: if the child writes more than that and nobody reads, the child blocks on its next write and never finishes. Use `stdio: 'ignore'` for output you do not want. ## The exit code: 'close' versus 'exit' | Event | Fires when | Arguments | |---|---|---| | `'spawn'` | the process started successfully | none | | `'exit'` | the process ended; stdio may still be open | `(code, signal)` | | `'close'` | the process ended **and** all its stdio streams closed | `(code, signal)` | | `'error'` | the process could not be spawned or killed, a message send failed, or an `AbortSignal` aborted it | `(err)` | **`code`** is the exit status when the program exited on its own; **`signal`** is a name such as `'SIGTERM'` when a signal terminated it. Node's documentation guarantees that one of the two is always non-`null`. A non-zero code is *not* an error event: it is simply a number your code has to check. Prefer `'close'` when you need the output, because several processes can share the same stdio streams and `'exit'` may fire before the last chunk has been read. The same facts are available afterwards as `subprocess.exitCode` and `subprocess.signalCode`. ## When the program never starts A missing executable is reported **asynchronously**, never as a synchronous throw from `spawn()` (which throws only for invalid arguments such as an empty command string). When the operating system cannot start the program: 1. `subprocess.pid` is `undefined`, and the `'spawn'` event is never emitted. 2. Node emits `'error'` with an `Error` whose `code` is `'ENOENT'` and whose `syscall` names the command, for example `spawn no-such-converter`. The same happens when `cwd` points at a directory that does not exist. 3. `'exit'` is not emitted for this failure, but `'close'` still follows the error. The trap is the second step. An `EventEmitter` that emits `'error'` with no listener **throws** the error, so a service that never attached one crashes the first time the binary is missing from a host. Attach the listener, or await the child with `events.once()`, which rejects when `'error'` fires first. ## A complete pattern ```js import { spawn } from 'node:child_process'; import { once } from 'node:events'; const child = spawn('ls', ['-l']); let output = ''; child.stdout.setEncoding('utf8'); child.stdout.on('data', (chunk) => { output += chunk; }); try { const [code, signal] = await once(child, 'close'); if (code !== 0) console.error(`ls failed: code=${code} signal=${signal}`); } catch (err) { console.error(`could not start ls: ${err.code}`); } ``` ## Mistakes interviewers listen for - Treating a non-zero exit as an `'error'` event: the code arrives in `'close'` and `'exit'`, and `'error'` means Node itself could not do something. - Reading the final output in `'exit'`, which can run before the streams have drained. - Forgetting that a chunk is a `Buffer`, then concatenating raw bytes and corrupting a multibyte character at a chunk boundary. - Starting a child with piped stdout and never reading it, then wondering why it hangs. - Assuming a missing program exits with status 127. That is what a *shell* reports; `spawn` without a shell gets `ENOENT`.

  • What does a missing program look like if you run it through exec instead of spawn?
    `exec()` starts a shell first (`/bin/sh` on Unix), and the shell itself starts fine, so there is no `ENOENT`. The shell prints a not-found message on stderr and exits with status 127, so `exec`'s callback receives an `Error` whose `code` is `127`. With `spawn` or `execFile` and no shell, the same mistake surfaces as an `'error'` event with `code === 'ENOENT'`.
  • Why can a child whose stdout you never read hang forever?
    With `stdio: 'pipe'` the child writes into a pipe of limited, platform-specific capacity. If the parent never consumes `subprocess.stdout`, the pipe fills, the child blocks on its next write, and it never exits, so `'close'` never fires. Either read the stream or spawn with `stdio: 'ignore'` or a file descriptor for output you do not need.

  • A non-zero exit code makes spawn emit an 'error' event.
  • The 'exit' event is the right place to read the child's final output.
  • subprocess.stdout delivers strings by default.
  • A missing binary simply exits with code 127 under spawn.
  • An 'error' event without a listener is silently ignored.