将可读流中的数据收集到变量中

时间:2015-04-02 04:52:47

标签: node.js stream

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

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

我不知道为什么,但实体属性在被管道传输后都是空的。如果我在this.entities函数中控制日志_write,则数据可用。

最终我想调用一个返回数组的函数,该数组的元素由Processor的数据块组成。 Collector看起来我是怎么做到的,但我还没走得很远。

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

1 个答案:

答案 0 :(得分:1)

它返回空数组,因为您的流式传输尚未完成。你应该听完成事件,以便合理地获取你的实体数组:

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);
        });