我正在尝试实现可写流,该流将把写入其中的数据保存到变量中。这是可写流的实现:

var util = require('util');
var Writable = require('stream').Writable;

function Collector()
{
  Writable.call(this, {objectMode: true});
  this.entities = [];
};

util.inherits(Collector, Writable);

Collector.prototype._write = function (chunk, encoding, callback)
{
  this.entities.push(chunk);
  callback();
};


module.exports = Collector;


这就是我试图对其进行测试的方式:

var fs = require('fs');
var Tokenizer = require('./tokenizer');
var Processor = require('../parser');
var Collector = require('./collector.js');

var tokenizer = new Tokenizer();
var processor = new Processor();
var collector = new Collector();

var readable = fs.createReadStream('./test/fixtures/test.dxf');

readable.pipe(tokenizer)
        .pipe(parser)
        .pipe(processor); // if this is piped to stdout, lots of data

console.log(collector.entities); // logs an empty array


我不确定为什么,但是在通过管道传输所有实体属性后,entities属性为空。如果我在this.entities函数中管理日志_write,则该数据可用。

最终,我想调用一个返回数组的函数,该数组的元素由Processor中的数据块组成。 Collector冒犯了我如何去做,但是我还没有走的很远。

如何将可读流中的块存储到变量中并从函数返回它们?

最佳答案

它返回空数组,因为您的流传输尚未完成。您应该侦听finish事件,以便普遍获取您的实体数组:

var fs = require('fs');
var Tokenizer = require('./tokenizer');
var Processor = require('../parser');
var Collector = require('./collector.js');

var tokenizer = new Tokenizer();
var processor = new Processor();
var collector = new Collector();

var readable = fs.createReadStream('./test/fixtures/test.dxf');

readable.pipe(tokenizer)
        .pipe(parser)
        .pipe(processor)
        .on('finish', function() {
            console.log(collector.entities);
        });

关于node.js - 将数据从可读流收集到变量中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29405195/

10-11 23:02
查看更多