On this page

stream/iter 可迭代流

History
Source Code: lib/stream/iter.js

稳定性:1 - 实验性 – 通过 --experimental-stream-iter CLI 标志启用此 API。

node:stream/iter 模块提供一个基于可迭代对象构建的流式 API, 而非事件驱动的 Readable/Writable/Transform 类层次结构, 也非 Web Streams 的 ReadableStream/WritableStream/TransformStream 接口。

流以 <AsyncIterable>(异步)或 <Iterable>(同步)表示。并 没有可供扩展的基类 —— 任何 实现迭代器协议的对象都可以参与。转换是普通 函数或带有 transform 方法的对象。

数据以批次形式流动(每次迭代为 <Uint8Array>[]),以摊薄 异步操作的开销。

该模块实现了 WinterTC 的 可迭代流 API 草案。经典 流互操作函数(fromReadable()、fromWritable()、 toReadable()、toReadableSync() 和 toWritable())、 Broadcast.from()、Share.from()、SyncShare.fromSync() 以及 Stream 导出的协议符号是 Node.js 扩展,不属于 该草案的一部分。

import { from, pull, text } from 'node:stream/iter';
import { compressGzip, decompressGzip } from 'node:zlib/iter';

// 压缩和解压缩字符串
const compressed = pull(from('Hello, world!'), compressGzip());
const result = await text(pull(compressed, decompressGzip()));
console.log(result); // 'Hello, world!'

此 API 中的所有数据都以 <Uint8Array> 字节表示。字符串 在传给 from()、push() 或 pipeTo() 时会自动进行 UTF-8 编码。这消除了编码方面的歧义,并实现了 流与原生代码之间的零拷贝传输。

每次迭代产生一个批次 —— 由 <Uint8Array> 数据块组成的 <Array> (<Uint8Array>[])。批处理将 await 和 <Promise> 创建的开销 摊薄到多个数据块上。一次只处理一个数据块的消费者可以 直接遍历内部数组:

for await (const batch of source) {
  for (const chunk of batch) {
    handle(chunk);
  }
}

转换有两种形式:

  • 无状态 —— 一个函数 (chunks, options) => result,每个批次调用 一次。接收 Uint8Array[](或 null 作为刷新信号)和一个 options 对象。返回 <Uint8Array>[] | <null> | <Iterable>。

  • 有状态 —— 一个对象 { transform(source, options) },其中 transform 是一个生成器(同步或异步),接收整个上游可迭代对象 和一个 options 对象,并产出输出。这种形式用于 压缩、加密,以及任何需要跨批次缓冲的 转换。

两种形式都会接收一个 options 参数,该参数具有以下属性:

Attributes
options.signal:<AbortSignal>
一个 AbortSignal,当管道 被取消、遇到错误或消费者停止读取时触发。转换 可以检查  signal.aborted 或监听 'abort' 事件,以便 提前执行清理。

刷新信号(null)在源结束后发送,让转换 有机会输出尾部数据(例如压缩尾注)。

// 无状态:大写转换
const upper = (chunks) => {
  if (chunks === null) return null; // flush
  return chunks.map((c) => new TextEncoder().encode(
    new TextDecoder().decode(c).toUpperCase(),
  ));
};

// 有状态:按行拆分器
const lines = {
  transform: async function*(source) {
    let partial = '';
    for await (const chunks of source) {
      if (chunks === null) {
        if (partial) yield [new TextEncoder().encode(partial)];
        continue;
      }
      for (const chunk of chunks) {
        const str = partial + new TextDecoder().decode(chunk);
        const parts = str.split('\n');
        partial = parts.pop();
        for (const line of parts) {
          yield [new TextEncoder().encode(`${line}\n`)];
        }
      }
    }
  },
};

该 API 支持两种模型:

  • 拉取 —— 数据按需流动。pull() 和 pullSync() 创建惰性 管道,仅在消费者迭代时才从源读取数据。

  • 推送 —— 数据被显式写入。push() 创建一个 writer/readable 对,并带有背压。writer 将数据推入;readable 作为 异步可迭代对象被消费。

拉取流具有天然的背压 —— 由消费者掌控节奏,因此 读取源的速度永远不会超过消费者处理的速度。推送流 则需要显式背压,因为生产者和消费者 独立运行。push()、broadcast() 和 share() 上的 budget 与 backpressure 选项控制其工作方式。

推送流使用由两部分组成的缓冲系统。可以把它想象成一个水桶 (缓冲区),通过一根水管(待处理写入)注水,并带有一个浮阀 当水桶装满时该浮阀会关闭:

                          budget (e.g., 16384)
                                 |
    Producer                     v
       |                    +---------+
       v                    |         |
  [ write() ] ----+    +--->| buffer  |---> Consumer pulls
  [ write() ]     |    |    | (bucket)|     for await (...)
  [ write() ]     v    |    +---------+
              +--------+         ^
              | pending|         |
              | writes |    float valve
              | (hose) |    (backpressure)
              +--------+
                   ^
                   |
          'strict' mode limits this too!
  • 缓冲区(水桶) —— 供消费者使用的数据,上限为 budget 字节。当消费者拉取时,会一次性排空所有缓冲数据 并放入单个批次中。

  • 待处理写入(水管) —— 等待缓冲区空间的写入。在 消费者排空后,待处理写入会被提升到现已腾空的 缓冲区中,其对应的 promise 随之敲定。

各策略如何使用这些缓冲区:

策略缓冲区上限待处理写入上限
'strict'budget1
'unbounded'budget无界
'drop-oldest'budget不适用(从不等待)
'drop-newest'budget不适用(从不等待)

严格模式用于捕获"即发即弃"模式,即生产者调用 write() 而不等待,这会导致内存无界增长。 它将缓冲区限制为 budget 字节,并将待处理写入队列 限制为单个条目。

如果你正确地等待每次写入,那么同一时间最多只会有一个待处理 写入(你自己的),因此永远不会触及待处理写入上限。 未等待的写入会在待处理队列中累积,一旦队列 溢出就会抛出异常:

import { push, text } from 'node:stream/iter';

const { writer, readable } = push({ budget: 16384 });

// 消费者必须并发运行 —— 否则,第一次写入
// 填满缓冲区后将永远阻塞生产者。
const consuming = text(readable);

// 正确做法:等待写入。当缓冲区满时,生产者会等待消费者
// 腾出空间。
for (const item of dataset) {
  await writer.write(item);
}
await writer.end();
console.log(await consuming);

忘记 await 最终会抛出异常:

// 错误做法:即发即弃。两个缓冲区都填满后,严格模式会抛出异常。
for (const item of dataset) {
  writer.write(item); // Not awaited -- queues without bound
}
// --> 抛出 "违反背压规则:待处理写入过多"

无界模式将缓冲字节数限制为 budget,但对 待处理写入队列不设上限。已等待的写入会阻塞,直到消费者腾出空间, 与严格模式一样。区别在于未等待的写入会静默地 永久排队而不抛出异常 —— 如果生产者忘记 await,这可能造成内存泄漏。

现有的 Node.js 经典流和 Web Streams 默认 采用的就是这种模式。当你能控制生产者并知道它会正确 等待时,或者从那些 API 迁移代码时,可以使用它。

import { push, text } from 'node:stream/iter';

const { writer, readable } = push({
  budget: 16384,
  backpressure: 'unbounded',
});

const consuming = text(readable);

// 安全 —— 等待写入会阻塞,直到消费者读取。
for (const item of dataset) {
  await writer.write(item);
}
await writer.end();
console.log(await consuming);

写入永不等待。当槽位缓冲区已满时,会淘汰最旧的缓冲 数据块,为传入的写入腾出空间。消费者 始终能看到最新的数据。适用于实时信息流、遥测,或 任何陈旧数据不如当前数据重要的场景。

import { push } from 'node:stream/iter';

// 只保留最近约 16 KB 的读数
const { writer, readable } = push({
  budget: 16384,
  backpressure: 'drop-oldest',
});

写入永不等待。当槽位缓冲区已满时,传入的写入会被 静默丢弃。消费者处理已缓冲的数据, 而不会被新数据淹没。适用于限流或 在压力下卸载负载。

import { push } from 'node:stream/iter';

// 最多接受 16 KB 的缓冲数据;超出部分一律丢弃
const { writer, readable } = push({
  budget: 16384,
  backpressure: 'drop-newest',
});

writer 是任何符合 Writer 接口的对象。只有 write() 是 必需的;其他所有方法都是可选的。

Writer 的参数使用 Web IDL 转换语义。非 Uint8Array 的数据块会 转换为 USVString,然后进行 UTF-8 编码。writev() 和 writevSync() 接受任何其值可转换为数据块的 可迭代对象。Writer 的选项字典将 null 视为空字典,并 忽略未知成员。

参数在写入本身开始之前进行转换。如果转换过程中运行了 用户代码(例如 toString() 方法,或 writev() 的迭代器 参数),并且这些代码向同一个 writer 写入,那么这些写入会排在 正在转换其参数的写入之前,并且它们计入相同的 背压限制。

在调用 end() 或 endSync() 之后,直到所有缓冲数据都被 消费之前,writer 处于 关闭中 状态。在关闭中,canWrite 为 null, write() 和 writev() 以 TypeError 拒绝,writeSync() 和 writevSync() 返回 false,endSync() 返回 -1,再次调用 end() 会返回与第一次调用相同的 promise。

每个异步方法都有一个对应的同步 *Sync 方法,专为 尝试回退模式而设计:先尝试快速的同步路径,仅在 同步调用表明无法完成时,才回退到 异步版本:

if (!writer.writeSync(chunk)) await writer.write(chunk);
if (!writer.writevSync(chunks)) await writer.writev(chunks);
if (writer.endSync() < 0) await writer.end();
writer.fail(err);  // Always synchronous, no fallback needed
Attributes

如果槽位缓冲区有物理容量(缓冲数据 低于配置的字节预算),返回 true;如果预算已耗尽,返回 false;或者 如果 writer 已关闭或消费者已断开连接,返回 null。

此项报告的物理容量与背压策略无关。对于 'drop-oldest' 或 'drop-newest',即使此值为 false,写入仍会完成, 分别通过淘汰缓冲数据或丢弃传入数据来实现。

这是一个提示而非保证:状态可能在检查与 写入之间发生变化。请使用 ondrain() 等待容量,而不要轮询。

writer.end(options?): void
Attributes
options:<Object>
仅取消此操作。该信号只取消 待处理的  end() 调用;不会使 writer 本身失败。

表示不再写入任何数据。已经在等待缓冲区 空间的写入仍排在流结束之前,而之后的写入会失败。如果 仍有未完成的数据,则返回的 promise 会在消费者拉取 最后一个批次之后的 done: true 后兑现。如果没有缓冲或待处理的数据,则 writer 会立即关闭。

writer.endSync(): void
  • 返回:<number>,写入的总字节数;如果结束操作无法 同步完成,则为 -1。

writer.end() 的同步版本。返回值 -1 仅表示 该操作无法同步完成;无法断定 关闭是否已开始,也无法断定其未完成的原因。请使用 尝试回退模式来等待完成:

const result = writer.endSync();
if (result < 0) {
  writer.end();
}
writer.fail(reason?): void
Attributes
reason:<any>

使 writer 进入终止错误状态。如果 writer 已关闭 或已出错,则此操作无效。与 write() 和 end() 不同,fail() 始终是无条件同步的,因为使 writer 失败只是纯粹的状态 转换,无需执行任何异步工作。reason 会被原样存储和传播。 如果省略,则 reason 为 undefined。

writer[Symbol.asyncDispose](): void

如果 writer 处于打开状态,则调用 writer.fail()。如果 writer 在调用 end() 或 endSync() 后处于关闭中状态,则等待缓冲数据排空。如果 writer 已关闭或已出错,则立即兑现。

write(chunk, options?): void
Attributes
options:<Object>
仅取消此写入操作。该信号只取消 待处理的  write() 调用;不会使 writer 本身失败。

写入一个数据块。

writer.writeSync(chunk): void
Attributes

同步写入。不会阻塞;如果背压生效,则返回 false。

writer.writev(chunks, options?): void
Attributes
chunks:<Iterable>
options:<Object>
仅取消此写入操作。该信号只取消 待处理的  writev() 调用;不会使 writer 本身失败。

将多个数据块作为单个批次写入。

writer.writevSync(chunks): void
Attributes
chunks:<Iterable>

同步批量写入。

大多数函数既可作为命名导出使用,也可作为 Stream 命名空间对象的属性使用。经典流适配器(fromReadable()、 fromWritable()、toReadable()、toReadableSync() 和 toWritable())以及 静态辅助对象(Broadcast、Share 和 SyncShare)只是 命名导出。

// 命名导出
import { from, pull, bytes, Stream } from 'node:stream/iter';

// 命名空间访问
Stream.from('hello');

Iterable Streams API 定义的选项字典使用 Web IDL 转换语义。null 被视为空字典,未知 成员会被忽略,已知成员会在操作运行前 转换为其声明的类型。转换失败时使用 Node.js 错误码,例如 ERR_INVALID_ARG_TYPE、ERR_INVALID_ARG_VALUE 和 ERR_OUT_OF_RANGE。

// 命名导出
const { from, pull, bytes, Stream } = require('node:stream/iter');

// 命名空间访问
Stream.from('hello');

在模块说明符中包含 node: 前缀是可选的。

M

from

History
from(input): void
Attributes
不得为  null 或 undefined 。

根据给定的输入创建一个异步字节流。字符串会进行 UTF-8 编码。 ArrayBuffer 和 ArrayBufferView 值会被包装为 Uint8Array。数组 和 input 中的可迭代对象会被递归展平并规范化。展平后的 值可能会被拆分到由实现定义的有界批次中。

实现了 Symbol.for('Stream.toAsyncStreamable') 或 Symbol.for('Stream.toStreamable') 的对象会通过这些协议进行转换。 toAsyncStreamable 协议优先于 toStreamable,而后者又 优先于迭代协议(Symbol.asyncIterator、 Symbol.iterator)。

import { Buffer } from 'node:buffer';
import { from, text } from 'node:stream/iter';

console.log(await text(from('hello')));       // 'hello'
console.log(await text(from(Buffer.from('hello')))); // 'hello'
M

fromSync

History
fromSync(input): void
Attributes
不得为  null 或 undefined 。

from() 的同步版本。返回一个同步可迭代对象。不能接受 异步可迭代对象或 promise。实现了 Symbol.for('Stream.toStreamable') 的对象会通过该协议进行转换(优先于 Symbol.iterator)。toAsyncStreamable 协议被 完全忽略。

import { fromSync, textSync } from 'node:stream/iter';

console.log(textSync(fromSync('hello'))); // 'hello'
M

pipeTo

History
pipeTo(source, ...transforms?, writer, options?): void
Attributes
数据源。
...transforms:<Function> | <Object>
要应用的一个或多个转换。
writer:<Object>
带有  write(chunk) 方法的目标。
options:<Object>
中止管道。中止会使目标 writer 失败,除非  preventFail 为 true 。
preventClose:<boolean>
如果为  true ,则当源结束时 不调用 writer.end() 。 默认值: false 。
preventFail:<boolean>
如果为  true ,则出错时不调用 writer.fail() 。 默认值: false 。

将源经过转换后管道连接到 writer。如果 writer 具有 writev(chunks) 方法,则整批数据会在单次调用中传入(从而实现 分散/聚集 I/O)。

如果 writer 实现了可选的 *Sync 方法(writeSync、writevSync、 endSync),pipeTo() 会先尝试使用同步方法 作为快速路径,仅在同步方法表明无法完成时,才回退到 异步版本(例如遇到背压或等待 下一个 tick)。fail() 始终以同步方式调用。

import { from, pipeTo } from 'node:stream/iter';
import { compressGzip } from 'node:zlib/iter';
import { open } from 'node:fs/promises';

const fh = await open('output.gz', 'w');
const totalBytes = await pipeTo(
  from('Hello, world!'),
  compressGzip(),
  fh.writer({ autoClose: true }),
);
M

pipeToSync

History
pipeToSync(source, ...transforms?, writer, options?): void
Attributes
source:<Iterable>
同步数据源。
...transforms:<Function> | <Object>
零个或多个同步转换。
writer:<Object>
带有  write(chunk) 方法的目标。
options:<Object>
failOnIncompleteClose:<boolean>
如果为  true ,则当 writer.endSync() 无法同步关闭 writer 时调用 writer.fail() 。当 preventFail 为 true 时忽略此选项。此选项是 Node.js 扩展。 默认值: false 。
preventClose:<boolean>
默认值: false 。
preventFail:<boolean>
默认值: false 。

pipeTo() 的同步版本。source、所有转换和 writer 必须是同步的。不能接受异步可迭代对象或 promise。

writer 必须具有 *Sync 方法(writeSync、writevSync、 endSync)和 fail(),才能正常工作。

pipeToSync() 绝不会回退到异步 writer 方法。如果 writer.endSync() 因为 writer 无法同步关闭而返回 -1 (例如,一个 push() writer 的消费者尚未读取全部数据 ),pipeToSync() 会抛出 ERR_INVALID_STATE。此时所有数据都已被接受, 因此默认情况下 writer 不会被置为失败:它仍然可以关闭,例如 通过 await writer.end()。如果无法通过其他方式关闭 writer (例如它没有 end() 方法),或者调用方不会关闭它, 则设置 failOnIncompleteClose,以抛出的错误将其置为失败。

M

pull

History
pull(source, ...transforms?, options?): void
Attributes
数据源。
...transforms:<Function> | <Object>
要应用的一个或多个转换。
options:<Object>
中止管道。

创建一个惰性异步管道。源转换和流化协议 分派在调用 pull() 时发生,但直到返回的 可迭代对象被消费时才会从 source 读取数据。转换按顺序应用。

当 signal 中止时,待处理的读取(或下一次读取)会以 signal.reason 拒绝,之后每次读取也是如此。如果 signal 已经中止, pull() 仍会返回一个可迭代对象;读取它会以 signal.reason 拒绝,而不会从 source 读取。

import { from, pull, text } from 'node:stream/iter';

const asciiUpper = (chunks) => {
  if (chunks === null) return null;
  return chunks.map((c) => {
    for (let i = 0; i < c.length; i++) {
      c[i] -= (c[i] >= 97 && c[i] <= 122) * 32;
    }
    return c;
  });
};

const result = pull(from('hello'), asciiUpper);
console.log(await text(result)); // 'HELLO'

使用 AbortSignal:

import { pull } from 'node:stream/iter';

const ac = new AbortController();
const result = pull(source, transform, { signal: ac.signal });
ac.abort(); // Pipeline throws AbortError on next iteration
M

pullSync

History
pullSync(source, ...transforms?): void
Attributes
source:<Iterable>
同步数据源。
...transforms:<Function> | <Object>
零个或多个同步转换。

pull() 的同步版本。源转换和流化协议 分派在调用 pullSync() 时发生。所有转换都必须是同步的。

M

push

History
push(...transforms?, options?): void
Attributes
...transforms:<Function> | <Object>
应用到可读一侧的可选 转换。
options:<Object>
budget:<number>
应用背压之前可缓冲的最大字节数。 必须为正整数。  默认值: 16384 。
backpressure:<string>
背压策略: 'strict' 、 'unbounded' 、 'drop-oldest' 或 'drop-newest' 。 默认值: 'strict' 。
中止流。在  writer.end() 之后缓冲数据排空期间, 该信号仍然有效;在此期间中止会使 writer 失败并拒绝 待处理的 end() promise。
writer:<Writable>
writer 一侧。
,其数据块以 <Uint8Array> [] 兑现。

创建一个带背压的推送流。writer 将数据推入; readable 一侧作为异步可迭代对象被消费。

import { push, text } from 'node:stream/iter';

const { writer, readable } = push();

// 生产者和消费者必须并发运行。在严格背压
(默认)下,等待的写入会阻塞,直到消费者读取。
const producing = (async () => {
  await writer.write('hello');
  await writer.write(' world');
  await writer.end();
})();

console.log(await text(readable)); // 'hello world'
await producing;

push() 返回的 writer 符合 [Writer 接口][]。

零长度的数据块无需缓冲即可被接受:它们不会被 传递给消费者,并且 writeSync() 和 write() 会为它们报告成功,即使 背压正在生效时也是如此。

M

duplex

History
duplex(options?): void
Attributes
options:<Object>
budget:<number>
两个方向的缓冲区大小(以字节为单位)。 必须为正整数。 默认值: 16384 。
backpressure:<string>
两个方向的策略。  默认值: 'strict' 。
两个通道的取消信号。
特定于 A 到 B 方向的选项。覆盖 共享选项。
budget:<number>
backpressure:<string>
特定于 B 到 A 方向的选项。覆盖 共享选项。
budget:<number>
backpressure:<string>

创建一对相连的双工通道以进行双向通信, 类似于 socketpair()。写入一个通道的 writer 的数据会出现在 另一个通道的 readable 中。

每个通道都有:

  • writer —— 一个用于向对端发送数据的 [Writer 接口][] 对象。
  • readable —— 一个用于从对端读取数据的 <AsyncIterable>。
  • close() —— 关闭通道的这一端(幂等)。
  • [Symbol.asyncDispose]() —— 为 await using 提供的异步释放支持。
import { duplex, text } from 'node:stream/iter';

const [client, server] = duplex();

// 服务端回显
const serving = (async () => {
  for await (const chunks of server.readable) {
    await server.writer.writev(chunks);
  }
  await server.writer.end();
})();

await client.writer.write('hello');
await client.writer.end();

console.log(await text(client.readable)); // 'hello'
await serving;
M

array

History
array(source, options?): void
Attributes
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

将所有数据块收集为一个由 Uint8Array 值组成的数组(不进行拼接)。

M

arrayBuffer

History
arrayBuffer(source, options?): void
Attributes
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

将所有字节收集到一个 ArrayBuffer 中。

M

arrayBufferSync

History
arrayBufferSync(source, options?): void
Attributes
source:<Iterable>
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

arrayBuffer() 的同步版本。

M

arraySync

History
arraySync(source, options?): void
Attributes
source:<Iterable>
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

array() 的同步版本。

M

bytes

History
bytes(source, options?): void
Attributes
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

将流中的所有字节收集到单个 Uint8Array 中。

import { from, bytes } from 'node:stream/iter';

const data = await bytes(from('hello'));
console.log(data); // Uint8Array(5) [ 104, 101, 108, 108, 111 ]
M

bytesSync

History
bytesSync(source, options?): void
Attributes
source:<Iterable>
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

bytes() 的同步版本。

M

dump

History
dump(source, options?): void
Attributes
,其数据块必须是 <Uint8Array> []。
options:<Object>
limit:<number>
要消费的最大字节数。如果读取的总字节数 超过 limit,则抛出  ERR_OUT_OF_RANGE 错误。

读取源直至完成,丢弃每一个数据块。与其他 消费者不同,dump() 不保留任何内容。无论源产生多少数据,内存 占用最多只达到单个批次。

当内容无关紧要时,可用此方法消费流。例如,一个 QUIC 流只在其数据被 消费时才向对端返还流控额度,因此不关心有效载荷的接收方仍必须 将其读取到完成。

如果源在中途发生错误,返回的 promise 会以该 错误拒绝。

没有默认的 limit。dump() 会一直读取直到源耗尽, 除非指定了限制。当配置了限制且源超出该限制时, promise 会被拒绝,且源会被取消。部分转储永远不会 被报告为成功。

import { dump, from, pull, tap } from 'node:stream/iter';

// 统计流过流的字节数,而不保留其中任何字节。
let bytesSeen = 0;
const counter = tap((chunks) => {
  for (const chunk of chunks) bytesSeen += chunk.byteLength;
});

await dump(pull(from('hello world'), counter));
console.log(bytesSeen); // 11
M

dumpSync

History
dumpSync(source, options?): void
Attributes
source:<Iterable>
,其数据块必须是 <Uint8Array> []
options:<Object>
limit:<number>
要消费的最大字节数。如果读取的总字节数 超过限制,则抛出  ERR_OUT_OF_RANGE 错误

dump() 的同步版本。如果 source 不是同步可迭代的, 则抛出 ERR_INVALID_ARG_TYPE 错误。

M

text

History
text(source, options?): void
Attributes
,其数据块必须是 <Uint8Array> []
options:<Object>
encoding:<string>
文本编码。 默认值: 'utf-8' 。
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过限制,则抛出  ERR_OUT_OF_RANGE 错误

收集所有字节并将其解码为文本。

import { from, text } from 'node:stream/iter';

console.log(await text(from('hello'))); // 'hello'
M

textSync

History
textSync(source, options?): void
Attributes
source:<Iterable>
,其数据块必须是 <Uint8Array> []
options:<Object>
encoding:<string>
默认值: 'utf-8' 。
limit:<number>
要消费的最大字节数。如果收集的总字节数 超过限制,则抛出  ERR_OUT_OF_RANGE 错误

text() 的同步版本。

M

ondrain

History
ondrain(drainable): void
Attributes
drainable:<Object>
实现 drainable 协议的对象。

等待可排空的写入器重新获得物理缓冲区容量。如果对象未实现 drainable 协议,则 返回 null;否则返回一个 promise,当缓冲数据降至字节预算以下时该 promise 以 true 兑现。

对于使用 'drop-oldest' 或 'drop-newest' 的写入器,即使写入不会阻塞,此方法也会 等待物理容量。这使生产者可以通过在写入前等待来避免数据 丢失。

import { push, ondrain, text } from 'node:stream/iter';

const { writer, readable } = push({ budget: 16384 });
const chunk = new Uint8Array(8192);  // 8 KB
writer.writeSync(chunk);
writer.writeSync(chunk);  // 16 KB total -- buffer full

// 开始消费,以便缓冲区能够真正排空
const consuming = text(readable);

// 缓冲区已满 -- 等待排空
const canWrite = await ondrain(writer);
if (canWrite) {
  await writer.write('c');
}
await writer.end();
await consuming;
M

merge

History
merge(...sources, options?): void
Attributes
,其数据块必须是 <Uint8Array> []
options:<Object>

通过按时间顺序产出批次(哪个源先产生数据就先产出哪个)来合并多个 异步可迭代对象。所有源都被 并发消费,每个源最多只有一个待处理的 next() 调用。

如果某个源失败,返回的可迭代对象会以其错误拒绝。merge() 会对其他源调用 return(),但不等待其完成:某个 暂停在 await 上的异步生成器源只会在该 await 完成后才运行其清理逻辑。

import { from, merge, text } from 'node:stream/iter';

const merged = merge(from('hello '), from('world'));
console.log(await text(merged)); // Order depends on timing
M

tap

History
tap(callback): void
Attributes
callback:<Function>
(chunks, options) => void 会在每个批次时调用,并在 源结束时使用 null 调用。 options.signal  是管道的 <AbortSignal> 。

创建一个透传转换,在不修改批次的情况下观察它们。 可用于日志记录、指标统计或调试。

import { from, pull, text, tap } from 'node:stream/iter';

const result = pull(
  from('hello'),
  tap((chunks) => {
    if (chunks !== null) console.log('Batch size:', chunks.length);
  }),
);
console.log(await text(result));

tap() 有意不阻止 tap 回调对 数据块进行原地修改;但返回值会被忽略。

M

tapSync

History
tapSync(callback): void
Attributes
callback:<Function>

tap() 的同步版本。

M

broadcast

History
broadcast(options?): void
Attributes
budget:<number>
缓冲区大小(以字节为单位)。必须是正整数。  默认值: 65536 。
backpressure:<string>
'strict' 、 'unbounded' 、 'drop-oldest' 或 'drop-newest' 。 默认值: 'strict' 。 'drop-newest' . 默认值: 'strict' .

创建一个推模型多消费者广播通道。单个写入器将数据推送 给多个消费者。每个消费者都有一个指向共享缓冲区的独立 游标。

import { broadcast, text } from 'node:stream/iter';

const { writer, broadcast: bc } = broadcast();

// 在写入前创建消费者
const c1 = bc.push();  // Consumer 1
const c2 = bc.push();  // Consumer 2

// 生产者和消费者必须并发运行。等待的写入
// 会在缓冲区填满时阻塞,直到消费者读取。
const producing = (async () => {
  await writer.write('hello');
  await writer.end();
})();

const [r1, r2] = await Promise.all([text(c1), text(c2)]);
console.log(r1); // 'hello'
console.log(r2); // 'hello'
await producing;
broadcast.cancel(reason?): void
Attributes
reason:<any>

取消广播。如果提供了 reason,所有消费者都会以该 确切的原因拒绝。如果省略,消费者会正常完成。

取消操作还会关闭配对的写入器:此后其 canWrite 为 null, 且 write() 会以 TypeError 拒绝。这使得 Broadcast.from() 的泵 停止从其源拉取数据。

Attributes

活跃消费者的数量。

broadcast.push(...transforms?, options?): void
Attributes
...transforms:<Function> | <Object>
options:<Object>

创建一个新的消费者。可选的转换会应用于该消费者看到的 数据视图。

broadcast[Symbol.dispose](): void

broadcast.cancel() 的别名。

M

Broadcast.from

History
Broadcast.from(input, options?): void
Attributes
options:<Object>
与  broadcast() 相同。

从已有的源创建 <BroadcastChannel>。源会被自动消费, 并推送给所有订阅者。

M

share

History
share(source, options?): void
Attributes
要共享的源。
options:<Object>
budget:<number>
缓冲区大小(以字节为单位)。必须是正整数。  默认值: 65536 。
backpressure:<string>
'strict' 、 'unbounded' 、 'drop-oldest' 或 'drop-newest' 。 默认值: 'strict' 。

创建一个拉模型多消费者共享流。与 broadcast() 不同, 只有在消费者拉取时才读取源。多个消费者共享一个 缓冲区。

使用 share.pull() 创建的消费者从仍在缓冲区中的最早条目 开始读取。一旦所有消费者都读取了条目,这些条目就会被释放。当 所有消费者都已分离后,缓冲的数据会保留给稍后附着的消费者, 并且源不会被关闭。调用 share.cancel()(或处置该 share) 即可在不再需要源时将其释放。

在 'strict' 背压下,当缓冲区达到或超过 budget 时,需要从源拉取数据的消费者 会被以 ERR_OUT_OF_RANGE 拒绝 并分离;该消费者后续的读取会以 { done: true } 完成。 分离机制可防止未被重试的消费者(例如使用 for await...of 进行的一次读取, 它在读取被拒绝时不会调用 return()) 占用缓冲数据并阻塞其他消费者。

在 'unbounded' 下,这样的消费者会等待最慢的消费者释放预算。在 'drop-newest' 下, 从源拉取的条目会被丢弃,然后该消费者以相同方式等待,因此在这两种情况下, 停滞的消费者也会拖慢排在它前面的消费者。只有 'drop-oldest' 能让前面的消费者继续,它会丢弃最慢的消费者尚未读取的最早缓冲条目。 从源拉取的批次如果大于 budget, 会先被拆分成更小的条目, 因此淘汰操作会保留预算范围内 最新的数据块。

import { from, share, text } from 'node:stream/iter';

const shared = share(from('hello'));

const c1 = shared.pull();
const c2 = shared.pull();

// 并发消费以避免小缓冲区导致的死锁。
const [r1, r2] = await Promise.all([text(c1), text(c2)]);
console.log(r1); // 'hello'
console.log(r2); // 'hello'

静态方法:Share.from(input[, options])

History
Attributes
options:<Object>
与  share() 相同。

从已有的源创建 <Share>。

share.cancel(reason?): void
Attributes
reason:<any>

取消共享。如果提供了 reason,所有消费者都会以该确切的 原因拒绝。如果省略,消费者会正常完成。

Attributes

活跃消费者的数量。

share.pull(...transforms?, options?): void
Attributes
...transforms:<Function> | <Object>
options:<Object>

创建共享源的一个新消费者。

share[Symbol.dispose](): void

share.cancel() 的别名。

Attributes
,返回一个 <Share> 。
Attributes
,返回一个 <SyncShare> 。
M

shareSync

History
shareSync(source, options?): void
Attributes
source:<Iterable>
要共享的同步源。
options:<Object>
budget:<number>
必须是正整数。  默认值: 65536 。
backpressure:<string>
'strict' 或 'drop-oldest' 。 默认值: 'strict' 。

share() 的同步版本。

同步消费者无法等待最慢的消费者释放预算, 而且当另一个消费者的读取正在进行时,最慢的消费者 也无法推进。因此不支持 'unbounded' 和 'drop-newest',并会 抛出 ERR_INVALID_ARG_VALUE。

Attributes
share.cancel(reason?): void
Attributes
reason:<any>

取消共享。如果提供了 reason,所有消费者都会抛出该确切的 原因。如果省略,消费者会正常完成。

Attributes

活跃消费者的数量。

share.pull(...transforms?): void
Attributes
...transforms:<Function> | <Object>

创建共享源的一个新消费者。

share[Symbol.dispose](): void

share.cancel() 的别名。

用于 pull()、pullSync()、 pipeTo() 和 pipeToSync() 的压缩与解压缩转换可通过 node:zlib/iter 模块获得。详情请参阅 node:zlib/iter 文档。

这些工具函数在经典 stream.Readable/stream.Writable 流与 stream/iter API 之间架起桥梁。

fromReadable() 和 fromWritable() 都接受鸭子类型的对象——它们 不要求输入直接继承 stream.Readable 或 stream.Writable。 下面描述了每个函数所需的最小契约。

M

fromReadable

History
fromReadable(readable): void

稳定性:1 - 实验性

Attributes
经典 Readable 流,或兼容的对象,该对象 具有  read() 、 pipe() 、 destroy() 、 on() 和 removeListener() 方法。

将经典 Readable 流(或鸭子类型的等价物)转换为 可传给 from()、 pull()、text() 等的 stream/iter 异步可迭代源。

如果对象实现了 toAsyncStreamable 协议(就像 stream.Readable 那样),则使用该协议。否则,函数 会对 read()、pipe()、destroy()、on() 和 removeListener() (EventEmitter)进行鸭子类型判断,并用带批处理的异步迭代器包装该流。

结果按实例缓存——用同一个流调用两次 fromReadable() 会返回 同一个可迭代对象。

对于对象模式或带编码的 Readable 流,数据块会自动 规范化为 Uint8Array。

import { Readable } from 'node:stream';
import { fromReadable, text } from 'node:stream/iter';

const readable = new Readable({
  read() { this.push('hello world'); this.push(null); },
});

const result = await text(fromReadable(readable));
console.log(result); // 'hello world'
M

fromWritable

History
fromWritable(writable, options?): void

稳定性:1 - 实验性

Attributes
经典 Writable 流,或兼容的对象, 具有  write() 、 end() 、 destroy() 、 on() 和 removeListener() 方法。
options:<Object>
backpressure:<string>
背压策略。 默认值: 'strict' 。
'strict':
当缓冲区已满时,一次写入可能会等待。在此写入被接受或取消之前, 后续写入都会被拒绝。
'unbounded':
当缓冲区已满时,写入会排队。推荐 与 pipeTo() 一起使用。
'drop-newest':
当缓冲区已满时,写入会被静默丢弃。
'drop-oldest':
不支持 。会抛出 ERR_INVALID_ARG_VALUE 。

从经典 Writable 流(或 鸭子类型的等价物)创建 stream/iter Writer 适配器。该适配器可作为 目标传给 pipeTo()。

由于经典 Writable 上的所有写入本质上都是异步的, 同步的 Writer 方法(writeSync、writevSync、endSync)总是 返回 false 或 -1,转而走异步路径。排队的 write() 或 writev() 在到达经典 Writable 之前,可以用其 options.signal 取消。

如果 writer.fail(reason) 收到非 Error 的原因,经典 Writable 会被 以 ERR_FALSY_VALUE_REJECTION 或 ERR_OPERATION_FAILED 错误销毁。 其 reason 属性包含原始值,该值仍是 Writer 存储的 失败原因。

结果按实例和背压策略缓存——用同一个流和 backpressure 选项 调用两次 fromWritable() 会返回 同一个 Writer。

对于未暴露 writableHighWaterMark、 writableLength 或类似属性的鸭子类型流,会使用合理的默认值。 对象模式的 Writable(如果可检测)会被拒绝,因为 Writer 接口仅支持字节。

import { Writable } from 'node:stream';
import { from, fromWritable, pipeTo } from 'node:stream/iter';

const writable = new Writable({
  write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
});

await pipeTo(from('hello world'),
             fromWritable(writable, { backpressure: 'unbounded' }));
M

toReadable

History
toReadable(source, options?): void

稳定性:1 - 实验性

Attributes
,其数据块必须以 <Uint8Array> [] 兑现, 即  pull() 或 from() 的返回值。
options:<Object>
highWaterMark:<number>
应用背压前的内部缓冲区大小(以字节为单位)。  默认值: 65536 (64 KB)。
用于中止 readable 的可选信号。

从 source 创建字节模式的 stream.Readable (stream/iter API 使用的原生批次格式)。产出批次中的每个 Uint8Array 都会作为 单独的数据块推入 Readable。

经典流无法将任意值表示为发出的错误。非 Error 的原因会被包装为 ERR_FALSY_VALUE_REJECTION 或 ERR_OPERATION_FAILED 错误,其 reason 属性包含原始 值。

import { createWriteStream } from 'node:fs';
import { from, pull, toReadable } from 'node:stream/iter';
import { compressGzip } from 'node:zlib/iter';

const source = pull(from('hello world'), compressGzip());
const readable = toReadable(source);

readable.pipe(createWriteStream('output.gz'));
M

toReadableSync

History
toReadableSync(source, options?): void

稳定性:1 - 实验性

Attributes
source:<Iterable>
,其数据块必须返回 <Uint8Array> [],例如  pullSync() 或 fromSync() 的返回值。
options:<Object>
highWaterMark:<number>
应用背压前的内部缓冲区大小(以字节为单位)。  默认值: 65536 (64 KB)。

从 source 创建字节模式的 stream.Readable。 _read() 方法会同步地从迭代器拉取数据, 因此可通过 readable.read() 立即获得数据。

import { fromSync, toReadableSync } from 'node:stream/iter';

const source = fromSync('hello world');
const readable = toReadableSync(source);

console.log(readable.read().toString()); // 'hello world'
M

toWritable

History
toWritable(writer): void

稳定性:1 - 实验性

Attributes
writer:<Object>
stream/iter Writer。只需要  write() 方法; end() 、 fail() 、 writeSync() 、 writevSync() 、 endSync() 和 writev() 是可选的。

创建一个由 stream/iter Writer 支撑的经典 stream.Writable。

每次 _write() / _writev() 调用都会先尝试 Writer 的同步方法 (writeSync / writevSync),如果同步路径返回 false,则回退到异步方法。 类似地,_final() 会先尝试 endSync() 再尝试 end()。当同步路径成功时,回调会通过 queueMicrotask 延迟执行,以保持异步解析约定。

经典流回调无法将任意值表示为错误。非 Error 的原因会被包装为 ERR_FALSY_VALUE_REJECTION 或 ERR_OPERATION_FAILED 错误,然后才传给回调。该错误的 reason 属性包含原始值。

在成功完成之前销毁 Writable 会调用 writer.fail()。 如果 fail() 不可用,且 Writer 实现了 Symbol.dispose 或 Symbol.asyncDispose, 则会使用它们。

Writable 使用经典流的默认 highWaterMark。经典流 背压会限制等待到达底层 Writer 的写入,而 Writer 控制当前 _write() 或 _writev() 操作的完成。

import { push, toWritable } from 'node:stream/iter';

const { writer, readable } = push();
const writable = toWritable(writer);

writable.write('hello');
writable.end();

这些众所周知的符号允许第三方对象参与流式协议, 而无需直接从 node:stream/iter 导入。

  • 值:Symbol.for('Stream.broadcastProtocol')

该值必须是一个函数。当 Broadcast.from() 调用它时,它会接收 传给 Broadcast.from() 的选项,并且必须返回一个符合 <BroadcastChannel> 接口的 对象。实现完全自定义——它可以 按任意方式管理消费者、缓冲和背压。

import {
  broadcast as createBroadcast,
  Broadcast,
  text,
} from 'node:stream/iter';

// 此示例沿用内置的 Broadcast,但自定义
// 实现可以使用任何机制。
class MessageBus {
  #broadcast;
  #writer;

  constructor() {
    const { writer, broadcast } = createBroadcast();
    this.#writer = writer;
    this.#broadcast = broadcast;
  }

  [Symbol.for('Stream.broadcastProtocol')](options) {
    return this.#broadcast;
  }

  send(data) {
    this.#writer.write(new TextEncoder().encode(data));
  }

  close() {
    this.#writer.end();
  }
}

const bus = new MessageBus();
const broadcast = Broadcast.from(bus);
const consumer = broadcast.push();
bus.send('hello');
bus.close();
console.log(await text(consumer)); // 'hello'
  • 值:Symbol.for('Stream.drainableProtocol')

实现此方法可使写入器与 ondrain() 兼容。如果没有背压,该方法应 返回 null,或者返回一个 promise,该 promise 会在背压消除时 以真值兑现。

import { ondrain } from 'node:stream/iter';

class CustomWriter {
  #queue = [];
  #drain = null;
  #closed = false;
  [Symbol.for('Stream.drainableProtocol')]() {
    if (this.#closed) return null;
    if (this.#queue.length < 3) return Promise.resolve(true);
    this.#drain ??= Promise.withResolvers();
    return this.#drain.promise;
  }
  write(chunk) {
    this.#queue.push(chunk);
  }
  flush() {
    this.#queue.length = 0;
    this.#drain?.resolve(true);
    this.#drain = null;
  }
  close() {
    this.#closed = true;
  }
}
const writer = new CustomWriter();
const ready = ondrain(writer);
console.log(ready); // Promise { true } -- no backpressure
  • 值:Symbol.for('Stream.shareProtocol')

该值必须是一个函数。当 Share.from() 调用它时,它会接收 传给 Share.from() 的选项,并且必须返回一个符合 <Share> 接口的 对象。实现完全自定义——它可以管理共享 源、消费者、缓冲和背压(方式不限)。

import { share, Share, text } from 'node:stream/iter';

// 此示例沿用内置的 share(),但自定义
// 实现可以使用任何机制。
class DataPool {
  #share;

  constructor(source) {
    this.#share = share(source);
  }

  [Symbol.for('Stream.shareProtocol')](options) {
    return this.#share;
  }
}

const pool = new DataPool(
  (async function* () {
    yield 'hello';
  })(),
);

const shared = Share.from(pool);
const consumer = shared.pull();
console.log(await text(consumer)); // 'hello'
  • 值:Symbol.for('Stream.shareSyncProtocol')

该值必须是一个函数。当 SyncShare.fromSync() 调用它时,它会接收 传给 SyncShare.fromSync() 的选项,并且必须返回一个符合 <SyncShare> 接口的对象。实现完全自定义——它可以管理 共享源、消费者和缓冲(方式不限)。

import { shareSync, SyncShare, textSync } from 'node:stream/iter';

// 此示例沿用内置的 shareSync(),但自定义
// 实现可以使用任何机制。
class SyncDataPool {
  #share;

  constructor(source) {
    this.#share = shareSync(source);
  }

  [Symbol.for('Stream.shareSyncProtocol')](options) {
    return this.#share;
  }
}

const encoder = new TextEncoder();
const pool = new SyncDataPool(
  function* () {
    yield [encoder.encode('hello')];
  }(),
);

const shared = SyncShare.fromSync(pool);
const consumer = shared.pull();
console.log(textSync(consumer)); // 'hello'
  • 值:Symbol.for('Stream.toAsyncStreamable')

该值必须是一个函数,用于将对象转换为可流式化的值。 当对象传给 from() 时,会调用此方法来产生 实际数据。它可以返回任何可解析为字符串、Uint8Array、 AsyncIterable、Iterable 或另一个可流式化对象的值。

import { from, text } from 'node:stream/iter';

class Greeting {
  #name;

  constructor(name) {
    this.#name = name;
  }

  [Symbol.for('Stream.toAsyncStreamable')]() {
    return `hello ${this.#name}`;
  }
}

const stream = from(new Greeting('world'));
console.log(await text(stream)); // 'hello world'
  • 值:Symbol.for('Stream.toStreamable')

该值必须是一个函数,用于同步地将对象转换为 可流式化的值。当对象传给 fromSync() 时,会调用此方法来产生 实际数据。它必须同步返回一个可流式化的值: 字符串、Uint8Array 或 Iterable。

import { fromSync, textSync } from 'node:stream/iter';

class Greeting {
  #name;

  constructor(name) {
    this.#name = name;
  }

  [Symbol.for('Stream.toStreamable')]() {
    return `hello ${this.#name}`;
  }
}

const stream = fromSync(new Greeting('world'));
console.log(textSync(stream)); // 'hello world'