Node.js

Read child-process output as a stream

Use spawn when child output should be consumed incrementally. Attach an error listener for launch failures and observe close for the final status after standard streams finish.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {spawn} from "node:child_process";
const child = spawn(process.execPath, ["-e", "process.stdout.write('stream ready')"]);
let text = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", chunk => { text += chunk; });
const code = await new Promise((resolve, reject) => {
  child.on("error", reject);
  child.on("close", resolve);
});
console.log(code, text);

How it works

The data listener receives chunks, not guaranteed complete lines. Waiting for close makes the captured tiny output ready for display. In a real large-output workflow, process or forward chunks rather than collecting the entire output as this small example does.

Limits and mistakes

Ignoring stderr or failing to consume piped output can cause incomplete diagnostics or stalled processes. A child may also end from a signal rather than a numeric exit code. Add timeouts and cancellation when external work can hang.

Check the result

Expect 0 stream ready. Try a failing executable path and a child that writes several chunks. Do not assume one data event corresponds to one printed line.

Sources

Reference documentation for the behavior used in this guide: