我正在尝试实现一个可写流,它将把写入其中的数据保存到一个变量中。这是可写流的实现:
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
我不知道为什么,但实体属性毕竟是空的。如果我在_write
函数中控制台记录this.entities
,则数据可用。
最终,我想调用一个函数,该函数返回一个数组,该数组的元素由Processor
中的数据块组成。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)
.on('finish', function() {
console.log(collector.entities);
});