6

Suppose I have created a transform stream called Parser which can be written to like a normal stream but is read from as an object stream. I am using the readable event for the code that uses this transform stream:

var parser = new Parser();
parser.on('readable', function () {
    var data = parser.read();
    console.log(data);
});

In this event handler, must I repeatedly call parser.read()? Or, will readable fire on its own for every single object being pushed from my transform stream?

thorn0
  • 9,362
  • 3
  • 68
  • 96
Brad
  • 159,648
  • 54
  • 349
  • 530

2 Answers2

6

According to the node docs, "Once the internal buffer is drained, a readable event will fire again when more data is available," so if you call read() just once and there's still more data to be read, you'll have to remember to read() some more later on.

You could call read() in a while loop (inside your 'readable' event handler) until it returns null, then wait for the next 'readable' event.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • So is it necessary to be in a while loop? The doc for readable.read() show that it's in a while loop. But it says that read() is going to empty the buffer. And if readable is going to be fired again, is it necessary to be in a while loop like the doc has shown? – huggie Jun 19 '14 at 08:11
  • upvoted! why cant I just use a "data" event instead of running a while loop inside readable event – PirateApp Nov 24 '18 at 05:45
  • 1
    @PirateApp You can. – mscdex Nov 26 '18 at 18:04
  • I have the same question, as the doc also says that "If the size argument is not specified, all of the data contained in the internal buffer will be returned.", so why is the `while` loop necessary though – Neekey May 16 '21 at 01:51
1

If you don't specify a size you only need to call it once per event fire. Readable will fire on its own each time there is more data.

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

fmsf
  • 36,317
  • 49
  • 147
  • 195