Node.js 将流式缓冲区转换回数字?
我有一个可读流的实现,它生成200个1-200之间的随机数:Node.js 将流式缓冲区转换回数字?,node.js,Node.js,我有一个可读流的实现,它生成200个1-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;
/*
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
中,我所要做的就是实例化流,并在它们进入时解码每个块。然而,我将jibberish作为我的输出——怎样才能让它打印出我所有的随机数
var Random = require('./random');
// Stream
var random = new Random();
random.on('data', function(chunk) {
console.log(chunk.toString('utf8'))
});
啊,明白了。缓冲区构造函数需要接受字符串,而不是整数。将buf
实例化行更改为:
var buf = new Buffer(randomNumber.toString());
成功了