Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
侦听Node.js流“可读”事件,导致无法读取源_Node.js_Stream_Node.js Stream_Readable - Fatal编程技术网

侦听Node.js流“可读”事件,导致无法读取源

侦听Node.js流“可读”事件,导致无法读取源,node.js,stream,node.js-stream,readable,Node.js,Stream,Node.js Stream,Readable,上述代码与预期和输出一样工作良好 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');

上述代码与预期和输出一样工作良好

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);
但是,当我将侦听器添加到事件“readable”时,不会读取任何数据

got here
chunk:some data

chunk:null
产出:

sourceReader.on('readable', function(){
  // it doesn't even get here
  var data = sourceReader.read();
  console.log(data); 
});
看起来像是SourceReader.\u read在源的可读事件被触发之前被调用,可能什么也不读。但随后source readable事件触发并调用SourceReader.read,但这一次不会进入SourceReader。\读取并完成

为什么会这样?那么,如果读取器有一个也触发可读事件的源,那么如何处理可读事件呢

谢谢你的回答

chunk:null
got here