How to pipe streams in Node.js
· Category: Node.js
Short answer
Use the .pipe() method on a readable stream to pass its output directly into a writable stream, handling backpressure automatically.
Steps
- Create a readable stream:
const readable = fs.createReadStream('source.txt');. - Create a writable stream:
const writable = fs.createWriteStream('dest.txt');. - Pipe them together:
readable.pipe(writable);. - Handle errors on the source stream:
readable.on('error', console.error);. - For transform streams like compression, chain pipes:
readable.pipe(gzip).pipe(writable);.
Tips
pipeline()from thestreammodule is a modern, promise-friendly alternative that properly cleans up and propagates errors.- Piping handles backpressure automatically by pausing the readable when the writable buffer is full.
Common issues
- Errors on the writable stream are not automatically forwarded from the readable; use
pipeline()or manual error listeners. - Calling
.pipe()after the readable has already emittedendwill not write any data.