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

  1. Create a readable stream: const readable = fs.createReadStream('source.txt');.
  2. Create a writable stream: const writable = fs.createWriteStream('dest.txt');.
  3. Pipe them together: readable.pipe(writable);.
  4. Handle errors on the source stream: readable.on('error', console.error);.
  5. For transform streams like compression, chain pipes: readable.pipe(gzip).pipe(writable);.

Tips

  • pipeline() from the stream module 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 emitted end will not write any data.