Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 将流式缓冲区转换回数字?_Node.js - Fatal编程技术网

Node.js 将流式缓冲区转换回数字?

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;

我有一个可读流的实现,它生成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;
};

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());
成功了