Why did stream.pipeline replace readable.pipe() as the way to chain Node.js streams, such as a gzip stage feeding an HTTP response?
answer
- both handle backpressure
- where does an error go
- who closes the other streams
- one callback for the whole chain
basics
~20 sreadable.pipe() handles backpressure but not failure: errors are not forwarded along the chain and the other streams are not closed, so they leak. stream.pipeline forwards the first error, destroys every stream, and reports completion once.
solid answer
~40 s`pipe()` and `pipeline` both pause the source when the destination is full, so backpressure is not the difference; failure is. With `a.pipe(b).pipe(c)`, an error in `a` or `b` is not forwarded, so a trailing `.on('error')` only hears `c`, and any stream without its own listener can crash the process with an unhandled `'error'`. Node documents that when the source errors, the destination is not closed; and when a destination fails, `pipe()` only unpipes it, leaving the source paused with its file descriptor or socket open. `stream.pipeline(a, b, c, cb)`, or the promise form in `node:stream/promises`, attaches the listeners for you, calls `destroy(err)` on every stream that has not already finished, and settles once with the first error or success. It also accepts async generators and, in the promise form, an `AbortSignal`.
code
javascript · 19 linesimport http from 'node:http';
import { Readable, pipeline } from 'node:stream';
import { createGzip } from 'node:zlib';
function* rows() {
for (let i = 1; i <= 500_000; i++) yield `${i},customer-${i}\n`;
}
http.createServer((req, res) => {
res.setHeader('content-encoding', 'gzip');
// Fragile: this listener hears res only; a failure in the source or gzip
// is not forwarded, and a failed stage leaves the others open.
// Readable.from(rows()).pipe(createGzip()).pipe(res).on('error', console.error);
pipeline(Readable.from(rows()), createGzip(), res, (err) => {
if (err) console.error('export failed:', err.code ?? err.message);
});
}).listen(8080);go deeper
Remember that pipe() moves data but leaves error handling and closing to you, while pipeline does both.
Explain why errors are not forwarded through pipe(), what pipeline destroys on failure, and why its callback or promise is the single place to handle the outcome.
Discuss what leaks with pipe() in a long-running server, premature-close errors from disconnecting clients, and the trap of pipeline destroying res before you can send a 500.
Set the team default: the promise form of pipeline for every multi-stage stream, with lint or review rules flagging bare pipe() chains in request paths.
## What both methods do Chaining streams means connecting a **Readable** (a source of chunks), zero or more **Transforms** (such as `zlib.createGzip()`), and a **Writable** (a destination such as an HTTP response). Node offers two ways: - **`readable.pipe(destination)`**, the original method on every Readable. It returns the destination, so calls chain: `rows.pipe(gzip).pipe(res)`. - **`stream.pipeline(...streams, callback)`** from `node:stream`, or **`pipeline(...streams)`** from `node:stream/promises`, which returns a promise. Both manage **backpressure**: when a destination's `write()` returns `false`, the source is paused until `'drain'`. So "pipeline handles backpressure and pipe does not" is a myth; the difference is what happens when something goes wrong. ## What pipe() leaves to you 1. **Errors are not forwarded.** Each stream emits its own `'error'`. In `rows.pipe(gzip).pipe(res).on('error', handler)`, the handler is attached to `res` only. A failure in `rows` or `gzip` never reaches it. 2. **An unhandled 'error' crashes the process.** An EventEmitter that emits `'error'` with no listener throws. Any stage in a `pipe()` chain without its own listener is a crash waiting for a bad input. 3. **Other streams are not closed.** Node's documentation states that if the Readable errors, the Writable destination is not closed automatically, and each stream must be closed manually to avoid leaks. The source itself destroys itself on error (`autoDestroy` defaults to `true`), but the stages after it stay open. 4. **A failed destination leaves the source dangling.** When a destination errors, `pipe()` only unpipes it. The source is left paused, holding its file descriptor or socket, with nothing to resume or destroy it. 5. **No single completion signal.** To know the chain finished, you watch `'finish'` on the last stream and hope nothing upstream failed silently. ## What pipeline adds `stream.pipeline` was introduced to replace that manual work: - **Error forwarding**: it listens to every stream, and the first error is the one reported to the callback or used to reject the promise. - **Cleanup**: on error it calls `stream.destroy(err)` on every stream, except Readables that already emitted `'end'` or `'close'` and Writables that already emitted `'finish'` or `'close'`. File descriptors and sockets are released. - **One completion signal**: the callback runs, or the promise settles, once the whole chain is done, waiting for `'close'` on streams that emit it. - **Premature close detection**: a stream that closes without ending and without an error produces **`ERR_STREAM_PREMATURE_CLOSE`**, so a client that disconnects mid-download is reported rather than ignored. - **Generators**: sources and stages can be async generator functions, which is often simpler than a custom Transform. - **Cancellation**: the promise form takes `{ signal }`; aborting it destroys the pipeline with an `AbortError`. | Concern | `readable.pipe()` | `stream.pipeline` | |---|---|---| | Backpressure | Yes | Yes | | Error from a middle stage | Only on that stream's own listener | Delivered to one callback or promise | | Other streams after an error | Left open | Destroyed | | Completion | Watch the last stream yourself | One callback or promise | | Cancellation | Manual `destroy()` calls | `AbortSignal` in the promise form | ## Caveats that come with pipeline - **It destroys the destination too.** If an HTTP response is the last stage and an earlier stage fails, `res` is destroyed, which closes the socket. You cannot send a 500 body afterwards; open the source and check it before you write headers, or keep `res` out of the pipeline. - **Dangling listeners.** After completion, `pipeline` leaves its event listeners on the streams so that a late `'error'` from a badly behaved stream cannot crash the process. Do not reuse the streams after a failure. - **Generator sources must honour the signal.** A generator passed as the first stage receives `{ signal }`; if it awaits something long without passing that signal on, the pipeline cannot finish promptly when aborted. ## Migrating a pipe() chain 1. List the streams in order and pass them to `pipeline` from `node:stream/promises`. 2. Delete the per-stream `'error'` listeners and manual `destroy()` calls that only existed to clean up. 3. Wrap the `await` in `try`/`catch` and decide the response there, once. 4. Move headers and status decisions before the pipeline starts, or keep `res` out of it, because a failure will destroy it. ## The interview answer Pipe solved flow control; pipeline solved the lifecycle. Use the promise form inside `async` code, put it in `try`/`catch`, and reach for `pipe()` only when you deliberately want to manage errors and closing per stream.
- The last stage of a pipeline is an HTTP response and the source fails. Why can't the error callback send a 500 response?Because `pipeline` destroys every stream on error, including `res`, which destroys the socket. By the time the callback runs, the connection is gone. Validate or open the source before writing headers, or keep `res` outside the pipeline and respond after it settles.
- What is ERR_STREAM_PREMATURE_CLOSE and when does pipeline report it?It is the error `stream.pipeline` and `stream.finished` report when a stream closes without ending gracefully and without an explicit error, for example when the HTTP response is closed because the client disconnected. It tells you the chain did not complete even though no stage threw.
- pipe() ignores backpressure; only pipeline pauses the source
- An .on('error') at the end of a pipe() chain catches errors from every stage
- When the source of pipe() fails, the destination is closed automatically
- With res as the last stage, pipeline still lets you send a 500 after a stage fails
- pipeline only reports errors; you still destroy each stream yourself