← Back to Node.js, page 1

nodejs-0009 · Medium mid

Why is stream.pipeline preferred over readable.pipe(writable)?

pipe() forwards data and backpressure, but it does not forward errors or destroy the other streams. If one stage fails, the others can stay open and leak file handles or sockets. pipeline() connects the stages, passes the first error to one callback, and destroys all the streams.

Full answer

Both pipe and pipeline move data from a readable stream to a writable stream and respect backpressure. The difference is what happens when something goes wrong.

With pipe, each stream has its own 'error' event, and an error in one stream is not passed on. When the destination errors, the source is simply unpiped and left open. When the source errors, the destination is not ended. You must attach an error handler to every stream and destroy the others yourself. If you forget, a file descriptor or a socket stays open until the process ends, and an unhandled 'error' event can crash the process.

pipeline(...streams, callback) fixes this:

  • It listens for errors and close events on every stream.
  • On the first error it destroys all streams, so no handle is left open.
  • It calls the callback once, with the error or with nothing on success.
  • A promise version exists in node:stream/promises, which works well with async/await.
  • It also accepts async generator functions as middle stages.

For new code, use pipeline from node:stream/promises. Keep pipe for quick experiments.

javascript
const { Readable, Transform, Writable, pipeline } = require('node:stream');

function build() {
  const source = Readable.from(['a', 'b', 'c', 'd']);
  const failing = new Transform({
    transform(chunk, encoding, callback) {
      if (chunk.toString() === 'c') callback(new Error('bad record: c'));
      else callback(null, chunk);
    },
  });
  const sink = new Writable({ write(chunk, encoding, callback) { callback(); } });
  return { source, failing, sink };
}

// 1. pipe: the error stays on the middle stream.
const a = build();
a.failing.on('error', (e) => console.log('pipe: error seen only on the middle stream:', e.message));
a.source.pipe(a.failing).pipe(a.sink);

setTimeout(() => {
  console.log('pipe: source destroyed?', a.source.destroyed);

  // 2. pipeline: one callback, everything is cleaned up.
  const b = build();
  pipeline(b.source, b.failing, b.sink, (err) => {
    console.log('pipeline: callback got:', err.message);
    console.log('pipeline: source destroyed?', b.source.destroyed, '| sink destroyed?', b.sink.destroyed);
  });
}, 50);

After the same failure, the piped source stays open, while pipeline destroys every stream. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): pipe: error seen only on the middle stream: bad record: c pipe: source destroyed? false pipeline: callback got: bad record: c pipeline: source destroyed? true | sink destroyed? true

Key points

  • Both respect backpressure.
  • pipe does not forward errors or destroy streams.
  • pipeline calls one callback and destroys every stream on the first error.
  • stream/promises gives an awaitable pipeline.

Common mistakes

  • Adding an error handler to only one stream in a pipe chain.
  • Assuming the source closes itself when the destination fails.
  • Calling the callback-style pipeline inside an async function and forgetting to wait for it.
  • Catching errors with try/catch around pipe(). The errors are events, not exceptions.

Follow-ups

  • How do you cancel a pipeline from outside?
  • What does stream.finished do?
  • How do async generators work as pipeline stages?

Tips

  • Show the failure case in the answer, not only the definition.
  • Say 'file descriptor leak' to name a concrete risk of pipe.
  • Use require('node:stream/promises') in modern code samples.