How would you pipe the output of one child process directly into the input of another, replicating a shell pipeline in Node.js?
Short answer
Each child process's stdout and stdin are Node.js streams, so you can use .pipe() directly to connect one process's stdout to another's stdin, replicating a shell pipeline like 'cat file.txt | grep pattern' entirely within Node.js code, with all the usual stream backpressure…
Advertisement
AModel answer
Each child process's stdout and stdin are Node.js streams, so you can use .pipe() directly to connect one process's stdout to another's stdin, replicating a shell pipeline like 'cat file.txt | grep pattern' entirely within Node.js code, with all the usual stream backpressure handling applying automatically.
const { spawn } = require('node:child_process');
const cat = spawn('cat', ['large-file.txt']);
const grep = spawn('grep', ['error']);
cat.stdout.pipe(grep.stdin);
grep.stdout.pipe(process.stdout);Real-world example
A log-analysis script pipes a 'cat' process's output through a 'grep' child process to filter for error lines, then pipes that filtered output directly to the parent process's own stdout, replicating a familiar shell pipeline programmatically for use within a larger Node.js automation script.
Likely follow-ups
- How does backpressure propagate correctly through a multi-stage piped child process chain?
- What happens to the downstream process if the upstream process is killed mid-pipeline?
Related topics