stream.Readable.from(iterable[, options])
-
iterable<Iterable> 实现Symbol.asyncIterator或Symbol.iterator可迭代协议的对象。如果传递空值,则触发 'error' 事件。¥
iterable<Iterable> Object implementing theSymbol.asyncIteratororSymbol.iteratoriterable protocol. Emits an 'error' event if a null value is passed. -
options<Object> 提供给new stream.Readable([options])的选项。默认情况下,Readable.from()会将options.objectMode设置为true,除非通过将options.objectMode设置为false明确选择退出。¥
options<Object> Options provided tonew stream.Readable([options]). By default,Readable.from()will setoptions.objectModetotrue, unless this is explicitly opted out by settingoptions.objectModetofalse. -
¥Returns: <stream.Readable>
用于从迭代器中创建可读流的实用方法。
¥A utility method for creating readable streams out of iterators.
const { Readable } = require('node:stream');
async function * generate() {
yield 'hello';
yield 'streams';
}
const readable = Readable.from(generate());
readable.on('data', (chunk) => {
console.log(chunk);
}); 出于性能原因,调用 Readable.from(string) 或 Readable.from(buffer) 不会迭代字符串或缓冲区以匹配其他流语义。
¥Calling Readable.from(string) or Readable.from(buffer) will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.
如果将包含 promise 的 Iterable 对象作为参数传递,可能会导致未处理的拒绝。
¥If an Iterable object containing promises is passed as an argument,
it might result in unhandled rejection.
const { Readable } = require('node:stream');
Readable.from([
new Promise((resolve) => setTimeout(resolve('1'), 1500)),
new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection
]);