Friday, 5 May 2017

What does read(0) in node stream do?

Could anyone illustrate how read(0) in node stream works, and in which case it is necessary?

The official read(0) doc is here. It says:

There are some cases where it is necessary to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In such cases, it is possible to call readable.read(0), which will always return null.

I met one case where read(0) is necessary. It is from stream-handbook. The source code is:

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

The result is:

$ (echo abc; sleep 1; echo def; sleep 1; echo ghi) | node consume2.js 
<Buffer 61 62 63>
<Buffer 0a 64 65>
<Buffer 66 0a 67>
<Buffer 68 69 0a>

Comment out the read(0) sentence,

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

The result would be:

$ (echo abc; sleep 1; echo def; sleep 1; echo ghi) | node consume1.js 
<Buffer 61 62 63>
<Buffer 0a 64 65>
<Buffer 66 0a 67>

I experimented with the above code and found that if I removed sleep 1 from the subshell command, then read(0) sentence is not necessary.

I think here the subshell sends a 'end of stream' event to consumer1.js after sending ghi, but it seems consumer1.js does not receive the 'end of stream' event unless read(0) does something. When read(0) does something, the js file knows there is an'end of stream', and the readable is triggered once more.

So my questions are:

  1. What is read(0) doing here?
  2. Why does read(0) become unnecessary when sleep 1 is removed from the shell command
  3. Can any one provide more cases where read(0) is necessary? (I tried file stream instead of stdin as js file input, then read(0) is not necessary)

Thanks.



via nlite

No comments:

Post a Comment