我试图理解为什么这段代码中的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();
}
});
};
节点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
任何提示将不胜感激
最佳答案
我终于找到了这个难题的答案。
var X = new thermom({highWaterMark: 500 });
将在此队列中为您提供500个项目的缓冲区,同样,highWaterMark为5会将迭代减少到仅5。其记录在node.js中https://nodejs.org/api/stream.html#stream_new_stream_readable_options