0

I have the following code from the Stream library in Node. It's just for my understanding of how streams work. I dont understand the order in which the push and 'data' event callback occurs here, as shown in the output below.

const r = Stream.Readable()
r._read = function () {
    console.log("log1")
    this.push("hello1");
    this.push("hello2")
    this.push(null)
}

console.log("Begin")
console.log("1 ", r.readableFlowing)
r.push("1235")


r.on('data', (d) => {
    console.log("data event", d.toString());
    console.log("--")
})

r.push("test")
console.log("2 ", r.readableFlowing)


console.log("After Push")

r.on('end', () => console.log('End'));

The Output:

Begin
1  null
2  true
After Push
log1
data event 1235
--
data event test
--
data event hello1
--
data event hello2
--
End

I would have expected the following output, from my understanding that push() function (source: https://github.com/nodejs/readable-stream/blob/7fdb3b4ec5135e586d5c6695f7e08d04f268b1cb/lib/internal/streams/readable.js#L208) and EventEmitter callbacks are synchronous.

1 null 
data event 1235
--
log1
data event hello1
--
data event hello2
--
// Error -> push ('hello') not possible since stream closes  
// after push(null) 

Are push() functions actually asynchronous? If so, then shouldnt 'hello1' and 'hello2' and null be added to the callback queue after 'log1', and shouldnt 'test' be ignored?

sekaranp
  • 1
  • 1

0 Answers0