fromReadable(readable)
readable<stream.Readable> | <Object> 一个经典的可读流或任何具有read()和on()方法的对象。- 返回:AsyncIterable
一个流/迭代器异步可迭代源。
将经典的可读流(或动态类型等效流)转换为可作为流/迭代异步可迭代源传递给 from()、pull()、text() 等的对象。
🌐 Converts a classic Readable stream (or duck-typed equivalent) into a
stream/iter async iterable source that can be passed to from(),
pull(), text(), etc.
如果对象实现了 toAsyncStreamable 协议(如 stream.Readable 所做的那样),将使用该协议。否则,该函数会对 read() 和 on()(EventEmitter)进行动态类型检查,并使用批处理异步迭代器封装流。
🌐 If the object implements the toAsyncStreamable protocol (as
stream.Readable does), that protocol is used. Otherwise, the function
duck-types on read() and on() (EventEmitter) and wraps the stream with
a batched async iterator.
结果会被每个实例缓存——使用相同的流调用 fromReadable() 两次会返回相同的可迭代对象。
🌐 The result is cached per instance -- calling fromReadable() twice with the
same stream returns the same iterable.
对于对象模式或编码的可读流,数据块会自动归一化为 Uint8Array。
🌐 For object-mode or encoded Readable streams, chunks are automatically
normalized to 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'const { Readable } = require('node:stream');
const { fromReadable, text } = require('node:stream/iter');
const readable = new Readable({
read() { this.push('hello world'); this.push(null); },
});
async function run() {
const result = await text(fromReadable(readable));
console.log(result); // 'hello world'
}
run();