stream.Readable.from(iterable[, options])
iterable
<Iterable> 实现Symbol.asyncIterator
或Symbol.iterator
可迭代协议的对象。 如果传入空值,则触发 'error' 事件。options
<Object> 提供给new stream.Readable([options])
的选项。 默认情况下,Readable.from()
会将options.objectMode
设置为true
,除非通过将options.objectMode
设置为false
来明确选择退出。- 返回: <stream.Readable>
一个从迭代器中创建可读流的实用方法。
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)
不会迭代字符串或缓冲区以匹配其他流语义。
如果包含承诺的 Iterable
对象作为参数传递,可能会导致未处理的拒绝。
const { Readable } = require('node:stream');
Readable.from([
new Promise((resolve) => setTimeout(resolve('1'), 1500)),
new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // 未处理的拒绝
]);
iterable
<Iterable> Object implementing theSymbol.asyncIterator
orSymbol.iterator
iterable protocol. Emits an 'error' event if a null value is passed.options
<Object> Options provided tonew stream.Readable([options])
. By default,Readable.from()
will setoptions.objectMode
totrue
, unless this is explicitly opted out by settingoptions.objectMode
tofalse
.- 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);
});
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.
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
]);