← 中文资源

简体中文版本

用 finished 等流收尾

pipeline 负责组合多个流,finished 只等单个流落定:正常 end 后 resolve,destroy(err) 后以同一 promise reject,不用手工挂 error 监听。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

await 点把异步工作排成序列,拒绝落在取结果的那一行。导入清单标出了平台接触面:finished、PassThrough,全部来自 node:stream/promises、node:stream。 各个操作都建立在顶层绑定之上:sink、chunks、failing。

使用要点

  • 无需安装:node:stream/promises 随 Node.js 本体提供。
  • 直接运行文件,输出会带上标签,比如 chunks received:、rejected with:——输出的每一行都能指回产生它的那次调用。

常见问题

有第三方依赖吗?

不需要。导入解析到 Node.js 核心模块,运行时自带。

核心语句

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));

代码示例

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)
);