readable.iterator([options])


稳定性: 1 - 实验

  • options <Object>
    • destroyOnReturn <boolean> 当设置为 false 时,在异步迭代器上调用 return 或使用 breakreturnthrow 退出 for await...of 迭代不会销毁流。 默认值: true
  • 返回: <AsyncIterator> 消费流。

如果 for await...of 循环由 returnbreakthrow 退出,或者如果流在迭代期间发出错误,迭代器是否应该销毁流,则此方法创建的迭代器为用户提供了取消流销毁的选项。

const { Readable } = require('node:stream');

async function printIterator(readable) {
  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // false

  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // 将打印 2 然后打印 3
  }

  console.log(readable.destroyed); // true,流被完全消费了
}

async function printSymbolAsyncIterator(readable) {
  for await (const chunk of readable) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // true
}

async function showBoth() {
  await printIterator(Readable.from([1, 2, 3]));
  await printSymbolAsyncIterator(Readable.from([1, 2, 3]));
}

showBoth();

Stability: 1 - Experimental

  • options <Object>
    • destroyOnReturn <boolean> When set to false, calling return on the async iterator, or exiting a for await...of iteration using a break, return, or throw will not destroy the stream. Default: true.
  • Returns: <AsyncIterator> to consume the stream.

The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.

const { Readable } = require('node:stream');

async function printIterator(readable) {
  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // false

  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // Will print 2 and then 3
  }

  console.log(readable.destroyed); // True, stream was totally consumed
}

async function printSymbolAsyncIterator(readable) {
  for await (const chunk of readable) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // true
}

async function showBoth() {
  await printIterator(Readable.from([1, 2, 3]));
  await printSymbolAsyncIterator(Readable.from([1, 2, 3]));
}

showBoth();