我有一个可读流的实现,可以在1-200之间生成200个随机数:
/*
Readable that produces a list of 200 random numbers
*/
var stream = require('stream');
function Random(options) {
// Inherits from stream.Readable
stream.Readable.call(this, options);
this._counter = 1;
};
Random.prototype = Object.create(stream.Readable.prototype);
Random.prototype.constructor = stream.Readable;
// Called whenever data is required from the stream
Random.prototype._read = function() {
// Generate a random number between 1 and 200
var randomNumber = Math.floor((Math.random() * 200) + 1);
var buf = new Buffer(randomNumber, 'utf8');
this.push(buf);
this._counter++;
// Generate 200 random numbers, then stop by pushing null
if (this._counter > 200) {
this.push(null);
}
};
module.exports = Random;
在我的main.js
中,我试图做的就是实例化流并在每个块进入时对其进行解码。但是,我的输出会变得乱七八糟 - 是什么方法让它打印出我的所有随机数?
var Random = require('./random');
// Stream
var random = new Random();
random.on('data', function(chunk) {
console.log(chunk.toString('utf8'))
});
答案 0 :(得分:0)
buf
实例化行更改为:
var buf = new Buffer(randomNumber.toString());
做了这个伎俩。