Listening to Node.js stream 'readable' event causing source not to be read

139 Views Asked by At
var stream = require('stream');
var util = require('util');

function SourceReader(source){
  stream.Readable.call(this);
  this._buffer = '';
  this._source = source;
  source.on('readable', function(){
    console.log('got here');
    this.read();
  }.bind(this));
}
util.inherits(SourceReader, stream.Readable);

SourceReader.prototype._read = function(){
  var chunk = this._source.read(); 

  console.log('chunk:'+ chunk); 

  if(chunk !== null){
    this.push(chunk);
  }
  else
    this.push(null);
};

var fs = require('fs');
var fileStream = fs.createReadStream('my.txt'); //some data

var sourceReader = new SourceReader(fileStream);

The above code works well as expected and outputs

got here
chunk:some data

chunk:null

but when I added a listener to the event 'readable', no data gets read.

sourceReader.on('readable', function(){
  // it doesn't even get here
  var data = sourceReader.read();
  console.log(data); 
});

outputs:

chunk:null
got here

It seems like the SourceReader._read gets called before the source's readable event got fired and presumably reads nothing. But then source readable event fires and calls SourceReader.read() but this time doesn't go into SourceReader._read and finishes.

Why is it so? So how do I handle readable events if the reader has a source that also fires readable event?

Thanks for answering.

0

There are 0 best solutions below