Stream Finished Settles Or Rejects

Await stream completion with finished(): the promise settles when the stream drains and rejects when it is destroyed with an error.

JavascriptResilience

Code

javascriptsnippet
23 lines
import { finished } from "node:stream/promises";
import { PassThrough } from "node:stream";

// finished() returns a promise that settles on stream completion or
// rejects on error - pipeline composes streams, finished just waits for one
const sink = new PassThrough();
const chunks = [];
sink.on("data", (chunk) => chunks.push(chunk));

sink.write("alpha\n");
sink.write("beta\n");
sink.end();

await finished(sink);
console.log("chunks received:", chunks.join("").trim().split("\n"));

const failing = new PassThrough();
failing.on("data", () => {});
process.nextTick(() => failing.destroy(new Error("disk went away")));
await finished(failing).then(
  () => console.log("unexpected success"),
  (err) => console.log("rejected with:", err.message)
);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

chunks received: [
  'a', 'l', 'p',
  'h', 'a', 'b',
  'e', 't', 'a'
]
rejected with: disk went away

Reading the code

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. finished, PassThrough come from node:stream/promises, node:stream — Node.js core modules the runtime ships with.

Every step works over top-level bindings: sink, chunks, failing.

Points of care

  • The dependency surface is just node:stream/promises, and that one is built into Node.js.

Putting it to use

Look for the chunks received:, unexpected success, rejected with: prefixes over the course of a run; each tag says which step produced the line.

Core lines

await finished(failing).then(
  () => console.log("unexpected success"),
  (err) => console.log("rejected with:", err.message)
);
process.nextTick(() => failing.destroy(new Error("disk went away")));
sink.on("data", (chunk) => chunks.push(chunk));

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.