Monday, 15 May 2017

relation between 'data' event and _read() while implementing stream.Readable

I had a hard time trying to figure out the relations between 'data' event and _read() in my implementation of Readable class.

I'm implementing a Readable stream with a socket as the underlying resource. As far as my understanding, it listens to 'data' event and push() the data to internal queue:

this.socket.on('data', dat => {this.push(this.doSomething(dat));})

and it'd signal an 'data' event to notify its listener some data is available, and it seems that everything works. Then, my question is when _read() will be used? Does it serves as an passive way for consumer, like pipe() or writableStream, to read()?

class MyReadable extends stream.Readable {
  constructor(options) {
    super(options);
    this.socket = new Socket();
    this.socket.on('data', dat => {
      this.push(doSomething(dat));
    })
  }
  doSomething(dat) {
    ...
    return transformedData;
  }
}



via Chris Lin

No comments:

Post a Comment