为什么在 Node.js 中读取非流动模式流需要 while 循环?

编程入门 行业动态 更新时间:2024-10-04 19:33:49

为什么在 Node.js 中读取非流动<a href=https://www.elefans.com/category/jswz/34/1771241.html style=模式流需要 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 循环?

本文发布于:2024-05-30 14:06:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!