Node.js可读的self.push()在完成15次迭代后停止

时间:2017-11-01 09:50:59

标签: javascript node.js stream readable

我试图理解为什么此代码中的Readable = require('stream').Readable仅在node.js上运行15次。我用这一行省略了这一行X.on('data',function() {console.log('data')});,它无限重复,这是正确的。

start.js

console.log('Start Therm');
const thermom = require('./therm.js');

var X = new thermom();
X._read();

X.on('start',function() {console.log('start')});

// X.on('data',function() {console.log('data')});

X.on('end',function() {console.log('end')});
X.on('error',function() {console.log('error')});

therm.js

var Readable = require('stream').Readable;  
var util = require('util');
var _ = require('lodash');
var count=0;
function getTemperatureReadingFromThermometer(cb) {
  setTimeout(function() {
    cb(null, Math.round(Math.random() * 20 * 100)/100) 
  }, 10);
}


module.exports = Thermometer;

function Thermometer(options) {
  this.count = 0;
  if (! (this instanceof Thermometer)) {
    return new Thermometer(options);
  }
  if (! options) { 
    options = {};
  }
  options.objectMode = true;
  Readable.call(this, options);

}

util.inherits(Thermometer, Readable);


Thermometer.prototype._read = function read() {
  var self = this;

  getTemperatureReadingFromThermometer(
    function(err, temperature) {
    console.log('getTemperatureReadingFromThermometer :' + temperature );
    if (err) { 
      self.emit('error', err);
    } else {
      console.log('self.push(temperature) :  ' +  count++);
      self.push();
    }
  });
};

node start.js只输出15次迭代。

Start Therm
getTemperatureReadingFromThermometer :7.98
self.push(temperature) :  0
getTemperatureReadingFromThermometer :18.46
self.push(temperature) :  1
getTemperatureReadingFromThermometer :13.27
self.push(temperature) :  2
getTemperatureReadingFromThermometer :1.6
self.push(temperature) :  3
getTemperatureReadingFromThermometer :18.08
self.push(temperature) :  4
getTemperatureReadingFromThermometer :2.08
self.push(temperature) :  5
getTemperatureReadingFromThermometer :10.91
self.push(temperature) :  6
getTemperatureReadingFromThermometer :13
self.push(temperature) :  7
getTemperatureReadingFromThermometer :9.98
self.push(temperature) :  8
getTemperatureReadingFromThermometer :14.4
self.push(temperature) :  9
getTemperatureReadingFromThermometer :6.69
self.push(temperature) :  10
getTemperatureReadingFromThermometer :12.14
self.push(temperature) :  11
getTemperatureReadingFromThermometer :3.65
self.push(temperature) :  12
getTemperatureReadingFromThermometer :13.54
self.push(temperature) :  13
getTemperatureReadingFromThermometer :16.59
self.push(temperature) :  14
getTemperatureReadingFromThermometer :1.69
self.push(temperature) :  15

任何提示都将非常感谢

1 个答案:

答案 0 :(得分:0)

我终于找到了这个窘境的答案。

 var X = new thermom({highWaterMark: 500 }); 

在这个队列中会给你500个项目的缓冲区,同样,5的highWaterMark会将迭代次数减少到只有5.它在node.js中记录https://nodejs.org/api/stream.html#stream_new_stream_readable_options