模式流需要 while 循环?"/>
为什么在 Node.js 中读取非流动模式流需要 while 循环?
在 node.js 文档中,我遇到了以下代码
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.');
});
这是 node.js 文档中关于 while 循环用法的评论,说需要确保读取所有数据
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
我不明白为什么需要它,并尝试用
while
语句替换 if
,并且该过程在第一次读取后终止。为什么?
回答如下:
来自 node.js 文档
readable.read() 方法只能在暂停模式下运行的可读流上调用。在流动模式下,自动调用 readable.read() 直到内部缓冲区完全耗尽。
请注意,此方法仅适用于已被暂停的流。
更进一步,如果您了解 stream 是什么,您就会明白您需要处理数据块。
每次调用 readable.read() 都会返回一大块数据,或者返回 null。这些块没有连接起来。需要一个 while 循环来消耗当前缓冲区中的所有数据。
所以我希望你明白,如果你不循环遍历你的可读流并且只执行 1 次读取,你将不会获得完整的数据。
参考:https://nodejs/api/stream.html
更多推荐
为什么在 Node.js 中读取非流动模式流需要 while 循环?
发布评论