简体   繁体   中英

Node.js stream readable.read call repeatly

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM