readable.read([size])
参数
readable.read() 方法从内部缓冲区中读取数据并返回。如果没有数据可供读取,则返回null。默认情况下,除非使用 readable.setEncoding() 方法指定了编码或流在对象模式下运行,否则数据将作为 Buffer 对象返回。
可选的size 参数指定要读取的特定字节数。如果 size 字节不可读取,则将返回 null,除非流已结束,在这种情况下,将返回内部缓冲区中剩余的所有数据。
如果未指定size 参数,则将返回内部缓冲区中包含的所有数据。
size 参数必须小于或等于 1 GiB。
readable.read() 方法只能在以暂停模式运行的Readable 流上调用。在流动模式下,会自动调用readable.read(),直到内部缓冲区完全耗尽。
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
每次调用 readable.read() 都会返回一个数据块,或 null 。块没有连接。 while 循环是消耗当前在缓冲区中的所有数据所必需的。读取大文件时 .read() 可能会返回 null ,到目前为止已经消耗了所有缓冲的内容,但仍有更多数据尚未缓冲。在这种情况下,当缓冲区中有更多数据时,将发出一个新的 'readable' 事件。最后,当没有更多数据到来时,将发出 'end' 事件。
因此,要从 readable 读取文件的全部内容,有必要跨多个 'readable' 事件收集块:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
无论 size 参数的值如何,对象模式下的 Readable 流将始终从对 的调用返回单个项目。readable.read(size)
如果readable.read() 方法返回一个数据块,也会发出一个'data' 事件。
在发出 事件后调用 'end' 将返回 stream.read([size]) null 。不会引发运行时错误。
相关用法
- Node.js stream.Readable.resume()用法及代码示例
- Node.js stream.Readable.reduce(fn[, initial[, options]])用法及代码示例
- Node.js stream.Readable.take(limit[, options])用法及代码示例
- Node.js stream.Readable.pipe(destination[, options])用法及代码示例
- Node.js stream.Readable.setEncoding(encoding)用法及代码示例
- Node.js stream.Readable.some(fn[, options])用法及代码示例
- Node.js stream.Readable.map(fn[, options])用法及代码示例
- Node.js stream.Readable.toArray([options])用法及代码示例
- Node.js stream.Readable.isPaused()用法及代码示例
- Node.js stream.Readable.forEach(fn[, options])用法及代码示例
- Node.js stream.Readable.every(fn[, options])用法及代码示例
- Node.js stream.Readable.from()用法及代码示例
- Node.js stream.Readable.flatMap(fn[, options])用法及代码示例
- Node.js stream.Readable.unshift(chunk[, encoding])用法及代码示例
- Node.js stream.Readable.filter(fn[, options])用法及代码示例
- Node.js stream.Readable.asIndexedPairs([options])用法及代码示例
- Node.js stream.Readable.drop(limit[, options])用法及代码示例
- Node.js stream.Readable.iterator([options])用法及代码示例
- Node.js stream.Readable.wrap(stream)用法及代码示例
- Node.js stream.Readable.find(fn[, options])用法及代码示例
- Node.js stream.Readable.unpipe([destination])用法及代码示例
- Node.js stream.Readable.pause()用法及代码示例
- Node.js stream.Readable.from(iterable[, options])用法及代码示例
- Node.js stream.Writable.uncork()用法及代码示例
- Node.js stream.finished()用法及代码示例
注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 stream.Readable.read([size])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
