← Back to Node.js, page 6

nodejs-0102 · Medium mid

How do errors, abort signals and early closes behave in stream.pipeline, and what is ERR_STREAM_PREMATURE_CLOSE?

stream/promises pipeline rejects with the first error and destroys every stream. An AbortSignal rejects with AbortError and destroys the streams. If a stream closes before it has ended normally, for example a client disconnects, the error is ERR_STREAM_PREMATURE_CLOSE. An async generator stage can transform data, and an exception inside it fails the pipeline like any other error.

Full answer

pipeline from node:stream/promises returns a promise. It settles when the last stream finishes or when anything goes wrong, and in both cases it cleans up.

Cases to know:

  • Error in any stage: the promise rejects with that error, and all other streams are destroyed.
  • AbortSignal: pass { signal } as the last argument. When the signal aborts, the promise rejects with an AbortError and the streams are destroyed. This is how you add a timeout or tie a stream to a request.
  • Premature close: a stream that closes before it finished writing or reading normally produces ERR_STREAM_PREMATURE_CLOSE. For example, a destination socket that the client closed. It is usually a normal event for downloads, so log it at a low level.
  • Async generator stages: a function* async stage reads the previous stage with for await and yields chunks. It is shorter than a Transform. Throwing inside it rejects the pipeline.
  • stream.finished(stream) resolves when the stream is done and rejects when it errored or closed early. It is the tool for one stream when you do not use pipeline.

Rules that avoid leaks:

  • Prefer pipeline over pipe. pipe does not destroy the other streams on error.
  • Always handle the rejection. An unhandled pipeline rejection becomes an unhandled promise rejection.
  • Do not call destroy() on a stream and then wait for 'end'. A destroyed stream emits 'close', not 'end'.
  • For HTTP servers, pass the request or response in the pipeline so a closed connection stops the work.
javascript
const { pipeline, finished } = require('node:stream/promises');
const { Readable, Writable } = require('node:stream');

const endless = () => new Readable({ read() { setTimeout(() => this.push('x'), 5); } });
const sink = () => new Writable({ write(chunk, enc, cb) { cb(); } });

async function main() {
  // 1. Abort after 30 ms.
  const controller = new AbortController();
  const source1 = endless();
  const sink1 = sink();
  setTimeout(() => controller.abort(), 30);
  await pipeline(source1, sink1, { signal: controller.signal })
    .catch((err) => console.log('1. abort ->', err.name, '| source destroyed:', source1.destroyed, '| sink destroyed:', sink1.destroyed));

  // 2. The destination closes before the pipeline is done.
  const source2 = endless();
  const early = new Writable({ write(chunk, enc, cb) { cb(); this.destroy(); } });
  await pipeline(source2, early)
    .catch((err) => console.log('2. early close ->', err.code, '| source destroyed:', source2.destroyed));

  // 3. An async generator stage throws.
  await pipeline(
    Readable.from([1, 2, 3]),
    async function* (source) {
      for await (const n of source) {
        if (n === 2) throw new Error('bad item ' + n);
        yield String(n);
      }
    },
    sink(),
  ).catch((err) => console.log('3. generator stage ->', err.message));

  // 4. finished() on a stream that was destroyed without ending.
  const manual = new Readable({ read() {} });
  const watch = finished(manual).catch((err) => console.log('4. finished ->', err.code));
  manual.destroy();
  await watch;

  // 5. Success path, for comparison.
  const chunks = [];
  await pipeline(Readable.from(['a', 'b']), new Writable({ write(c, e, cb) { chunks.push(c.toString()); cb(); } }));
  console.log('5. success -> wrote', chunks.join(''));
}
main();

Each case ends with the stream error code or name. In every failing case the other streams are destroyed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. abort -> AbortError | source destroyed: true | sink destroyed: true 2. early close -> ERR_STREAM_PREMATURE_CLOSE | source destroyed: true 3. generator stage -> bad item 2 4. finished -> ERR_STREAM_PREMATURE_CLOSE 5. success -> wrote ab

Key points

  • pipeline rejects with the first error and destroys all streams.
  • { signal } turns an abort into an AbortError and cleans up.
  • A stream that closes too early gives ERR_STREAM_PREMATURE_CLOSE.
  • Async generator stages are the short way to write a transform.
  • finished() watches one stream for end, error or early close.

Common mistakes

  • Using pipe() and leaving the source open after the destination failed.
  • Not catching the pipeline promise.
  • Treating ERR_STREAM_PREMATURE_CLOSE on a download as a server bug.
  • Waiting for 'end' on a stream that was destroyed.
  • Passing the signal in the wrong position: it belongs in the options object at the end.

Follow-ups

  • How do you stop work when an HTTP client disconnects?
  • What is the difference between destroy() and end()?
  • How does stream.compose differ from pipeline?

Tips

  • Give the three outcomes: error, abort, premature close.
  • Show the async generator stage because it is short.
  • Mention that a download client closing is normal.