Must I repeatedly call readable.read() within a readable event handler?

邮差的信 提交于 2019-12-10 17:24:16

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23452846/must-i-repeatedly-call-readable-read-within-a-readable-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!