2015-09-03 28 views
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')) 
}); 

回答

0

Ahhh - 明白了。 Buffer构造函数需要接受一个字符串,而不是一个整数。更改buf实例行:

var buf = new Buffer(randomNumber.toString()); 

的伎俩。

相关问题