我试图理解为什么Readable = require('stream').Readable
在这个代码中只能在 node.js 上工作 15 次。我省略了这条线X.on('data',function() {console.log('data')});
,这条线无限重复,这是正确的。
开始.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')});
热.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
任何提示将不胜感激