In Node.js, when do you reach for stream.finished() and a stream's destroy() method instead of a 'finish' listener and end()?
answer
- graceful versus abrupt endings
- events that never fire
- flush first, or throw it away
- a premature close is an outcome too
basics
~20 s'end' and 'finish' fire only when a stream completes gracefully, so code waiting on them hangs after an error or abort. stream.finished() settles on every outcome. end() flushes buffered data; destroy() abandons the stream at once and releases its resources.
solid answer
~40 s`'end'` (Readable) and `'finish'` (Writable) only fire on a graceful finish. A stream that errors or is destroyed, such as the body of an aborted HTTP request, emits `'error'` and/or `'close'` instead, so code that only waits for `'finish'` never runs. `stream.finished(stream, cb)`, or `await finished(stream)` from `node:stream/promises`, settles once on success, on error, or on a premature close, reported as `ERR_STREAM_PREMATURE_CLOSE`, and it even settles for a stream that already finished. On the writing side, `end()` is the graceful close: flush the buffer, then `'finish'`. `destroy(err)` is immediate: unflushed writes may be lost, `'error'` (if you pass one) and `'close'` are emitted, the file descriptor or socket is released, and later `write()` calls fail with `ERR_STREAM_DESTROYED`. I use `end()` when the data matters and `destroy()` when I am abandoning the work.
code
javascript · 13 linesimport { createWriteStream } from 'node:fs';
import { finished } from 'node:stream/promises';
const out = createWriteStream('export.csv');
out.write('id,name\n');
out.end('1,first-row\n'); // graceful: write the last chunk, flush, then 'finish'
try {
await finished(out); // settles on 'finish', on 'error', or on a premature close
console.log('export.csv fully written');
} catch (err) {
console.error('write failed:', err.code);
}go deeper
Recall that 'finish' and 'end' mean success only, and that end() closes gracefully while destroy() stops immediately.
Explain what finished() reports, including ERR_STREAM_PREMATURE_CLOSE, and the differences between end() and destroy() in buffered data, events and later writes.
Show where these matter in a server: aborted requests that never emit 'end', abandoning work with destroy(err), and listener build-up from repeated finished() calls.
Set a team convention that waiting on a stream goes through finished() or pipeline, never a bare 'finish' listener, and that abandoned work is destroyed, not left running.
## Two ways a stream can stop Every Node.js stream ends in one of two ways: - **Gracefully**: a Readable delivers all its data and emits **`'end'`**; a Writable has `end()` called, flushes its buffer and emits **`'finish'`**. Then both usually emit **`'close'`** once their resources are released. - **Abruptly**: the stream errors or someone calls **`destroy()`**. It emits **`'error'`** (if there was one) and **`'close'`**, and it never emits `'end'` or `'finish'`. Since `autoDestroy` defaults to `true`, a stream destroys itself after a graceful end or an error, so `'close'` arrives in both cases. Code that only listens for the graceful event is only correct on the happy path. ## stream.finished(): one signal for every outcome `stream.finished(stream, callback)` from `node:stream`, or `finished(stream)` from `node:stream/promises`, tells you when a stream is **no longer readable or writable**, whatever the reason: - it calls back with no error after a graceful end; - it passes the stream's error if it failed; - it reports **`ERR_STREAM_PREMATURE_CLOSE`** when the stream closed without ending and without an explicit error, as when an HTTP response's connection drops before it finishes; - it still calls back if the stream had already finished before you called it, so there is no race with an event that already fired. Node's documentation singles out exactly that error-handling case: a stream destroyed prematurely, like an aborted HTTP request, will not emit `'end'` or `'finish'`. Two details matter in long-running services: 1. **Dangling listeners.** `finished()` leaves its `'error'`, `'end'`, `'finish'` and `'close'` listeners attached after it settles, deliberately, so a late `'error'` from a badly written stream cannot crash the process. Call the cleanup function the callback form returns, or pass `{ cleanup: true }` to the promise form, if you attach it many times to long-lived streams. 2. **Its signal does not destroy anything.** Passing `{ signal }` lets you stop *waiting*; the stream itself is **not** aborted. That differs from `pipeline`, whose signal destroys the streams. ## end() versus destroy() | | `writable.end()` | `writable.destroy([err])` | |---|---|---| | Buffered data | Flushed first | May be lost; earlier writes may fail with `ERR_STREAM_DESTROYED` | | Events | `'finish'`, then `'close'` | `'error'` (only if `err` given), then `'close'` | | Timing | After the buffer drains | Immediate | | Later `write()` | `ERR_STREAM_WRITE_AFTER_END` | `ERR_STREAM_DESTROYED` | | Use it when | The output must be complete | The work is being abandoned | `readable.destroy()` exists too: it releases the underlying resource, such as a file descriptor, and further `push()` calls are ignored. Calling it again later is a no-op, so cleanup code can call it defensively. ## Where these show up in practice - **Waiting for a single stream you do not pipe**, for example knowing when an upload response has been fully consumed, or detecting that a client closed the connection early: use `finished()`. - **Abandoning work**: the client of a CSV export disconnected, so destroy the gzip stream and the row source instead of letting them run; pass an error to `destroy(err)` if listeners should learn why. - **Shutting down cleanly**: call `end()` on a log or file writer so its buffer reaches disk, then await `finished()` before closing. - **Inside pipelines** you rarely call either: `stream.pipeline` uses the same end-of-stream detection as `finished()` and calls `destroy(err)` on every stage for you. ## finished() or pipeline()? Both detect the end of a stream the same way, but they own different amounts of work: | | `stream.finished()` | `stream.pipeline()` | |---|---|---| | Scope | One stream you observe | A chain it connects | | Moves data | No | Yes, with backpressure | | On failure | Reports it | Reports it and destroys every stage | | Its `signal` | Cancels the wait only | Destroys the chain | Use `finished()` to watch a stream someone else drives; use `pipeline` when you are the one connecting streams. ## Common mistakes - Waiting for `'finish'` on a stream that might fail, so the handler never resolves. - Calling `destroy()` on a file writer to "close" it and losing the last buffered chunk. - Overriding `destroy()` itself in a subclass; Node says implementers should implement `_destroy()` instead (writing stream subclasses is a separate subject).
- If you pass an AbortSignal to stream.finished() and it aborts, is the stream destroyed?No. The signal only cancels the wait: the callback or promise gets an `AbortError` and `finished()` removes its listeners, but the stream keeps running. To actually stop it, call `destroy()` yourself, or use `stream.pipeline`, whose signal does destroy the streams.
- Why does stream.finished() leave event listeners attached, and when does that matter?So that an `'error'` emitted late by a badly implemented stream still has a listener and does not crash the process. It matters when you call `finished()` repeatedly on long-lived streams: the listeners accumulate. Call the returned cleanup function, or pass `{ cleanup: true }` to the promise form.
- Listening for 'finish' is enough to know when a write stream is done
- destroy() is just a faster end(); buffered data still gets written
- Aborting the signal passed to stream.finished() destroys the stream
- A destroyed stream emits 'end' or 'finish' so waiting code can continue
- Calling destroy() twice throws, so cleanup code must track whether it already ran