【问题标题】:Streams read(0) instructionStreams read(0) 指令
【发布时间】:2014-11-04 07:06:37
【问题描述】:

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

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),它会打印出来

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

为什么?

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

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

它会打印出来

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

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

【问题讨论】:

    标签: node.js stream


    【解决方案1】:

    我这几天碰巧学习了 NodeJS 流模块。下面是Readable.prototype.read函数里面的一些cmets:

    // if we're doing read(0) to trigger a readable event, but we
    // already have a bunch of data in the buffer, then just trigger
    // the 'readable' event and move on.
    

    它说在调用.read(0) 之后,如果stream 没有结束,stream 只会触发(使用process.nextTick)另一个readable 事件。

    function emitReadable(stream) {
      // ...
      process.nextTick(emitReadable_, stream);
      // ...
    }
    

    【讨论】:

      【解决方案2】:

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

      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);
        }
      });
      

      你可以改变块的大小,通过 sleep 或不带它的输入...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        相关资源
        最近更新 更多