0
我有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'))
});