0

The question is actually asked already by Brad, but I don't find the question really answered yet. Must readable.read() inside a readable event handler be called repeatedly? In the current node documentation the example code read:

var readable = getReadableStreamSomehow();
readable.on('readable', function() {
  var chunk;
  while (null !== (chunk = readable.read())) {
    console.log('got %d bytes of data', chunk.length);
  }
});

readable.read() is called repeatedly.

The document says this about readable event:

Once the internal buffer is drained, a readable event will fire again when more data is available.

It also says this about read():

If you do not specify a size argument, then it will return all the data in the internal buffer.

So is there any case where putting it in a while loop to repeatably call read() necessary?

Community
  • 1
  • 1
huggie
  • 17,587
  • 27
  • 82
  • 139

2 Answers2

1

First of all, this will cause your server to block if the read never returns null:

  while (null !== (chunk = readable.read())) {
    console.log('got %d bytes of data', chunk.length);
  }

Unless you specify a size argument, you only need to call read once for each time the 'readable' event is fired. If you do specify a size, and the size is smaller than the total amount of data to read, then you have to call it as many times as it's needed.

You have readable.on('end', ... that will allow you to know when no more data is available.

fmsf
  • 36,317
  • 49
  • 147
  • 195
  • Then the example in the documentation stands corrected, I guess. – huggie Jul 02 '14 at 06:50
  • According to a talk prior to the then expected v.10 release (https://dl.dropboxusercontent.com/u/3685/presentations/streams2/streams2-ko.pdf), returning null is part of the specification. , readable event is only fired after it returns null. Maybe that's why the doc use a while loop. Maybe that's why it is necessary then? Because if you don't read till it's empty then it has not returned null yet. – huggie Jul 09 '14 at 00:46
  • Anyway, the documentation certainly doesn't reflect that null must be returned by readable.read() before another readble event, only that the buffer is empty. – huggie Jul 09 '14 at 00:54
0

in object mode, .read() only returns an object, so this would be necessary. i'm not sure if this is necessary for binary streams, but i've successfully only called .read() once per readable event in them.

Jonathan Ong
  • 19,927
  • 17
  • 79
  • 118