Node.js › Child Processes & Process Management
How would you pipe the output of one child process directly into the input of another, replicating a shell pipeline in Node.js?
IntermediateAnswer
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.