流读取(0)指令 [英] Streams read(0) instruction

查看:37
本文介绍了流读取(0)指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了一个代码 https://github.com/substack/stream-handbook 从流中读取 3 个字节.我不明白它是如何工作的.

There is a code I found here https://github.com/substack/stream-handbook which reads 3 bytes from stream. And I do not understand how it works.

process.stdin.on('readable', function() {
    var buf = process.stdin.read(3);
    console.log(buf);
    process.stdin.read(0);
});

被这样称呼:

(echo abc; sleep 1; echo def; sleep 1; echo ghi) | node consume.js

它返回:

<Buffer 61 62 63>
<Buffer 0a 64 65>
<Buffer 66 0a 67>
<Buffer 68 69 0a>

首先,为什么我需要这个 .read(0) 东西?在我通过 .read(size) 请求之前,流是否有一个缓冲区来存储其余数据?但是没有 .read(0) 它会打印

First of all, why do I need this .read(0) thing? Isn't stream has a buffer where the rest of data is stored until I request it by .read(size)? But without .read(0) it'll print

<Buffer 61 62 63>
<Buffer 0a 64 65>
<Buffer 66 0a 67>

为什么?

第二个是这些 sleep 1 指令.如果我在没有它的情况下调用脚本

The second is these sleep 1 instructions. If I call the script without it

(echo abc; echo def; echo ghi) | node consume.js

它会打印

<Buffer 61 62 63>
<Buffer 0a 64 65>

不管我会不会使用.read(0).我完全不明白这一点.这里用什么逻辑来打印这样的结果?

no matter will I use .read(0) or not. I don't understand this completely. What logic is used here to print such a result?

推荐答案

我不确定 https://github.com/substack/stream-handbook 尝试使用 read(0) 方法显示,但恕我直言,这是正确的方法:

I am not sure about what exactly the author of https://github.com/substack/stream-handbook tried to show using the read(0) approach, but IMHO this is the correct approach:

process.stdin.on('readable', function () {
  let buf;
  // Every time when the stream becomes readable (it can happen many times), 
  // read all available data from it's internal buffer in chunks of any necessary size.
  while (null !== (buf = process.stdin.read(3))) {
    console.dir(buf);
  }
});

您可以更改块大小,在睡眠或不睡眠的情况下传递输入...

You can change the chunk size, pass the input either with sleep or without it...

这篇关于流读取(0)指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆