完成流转换后的事件监听器Node.js

时间:2015-05-15 08:38:19

标签: node.js

  

我正在尝试在管道转换中的数据末尾注册事件监听器。我曾是   尝试将事件注册到管道中的所有流:

a)我的自定义转换流(StreamToBuffer)
b)标准文件读取流
c)标准的gunzip流。

  

但不幸的是,它们都不起作用(见下面的代码)。就我而言   尝试,只有'数据'事件有效,但它没有帮助。

我需要的是继续在转换完成后 StreamToBuffer 中处理 tailBuffer

你能建议如何实现这个目标吗?

代码(为简洁而简化):

function samplePipe() {
    var streamToBuffer = new StreamToBuffer();
    var readStream = fs.createReadStream(bgzFile1, { flags: 'r',
        encoding: null,
        fd: null,
        mode: '0666',
        autoClose: true
    });
    var gunzipTransform = zlib.createGunzip();
    readStream.on('end', function() {
        //not fired
        console.log('end event readStream');
    });
    streamToBuffer.on('end', function() {
        //not fired
        console.log('end event streamBuffer');
    });
    gunzipTransform.on('end', function() {
        //not fired
        console.log('end event gunzipTransform');
    });
    readStream
        .pipe(gunzipTransform)
        .pipe(streamToBuffer)
    ;
}

StreamToBuffer:

function StreamToBuffer() {
    stream.Transform.call(this);
    this.tailBuffer = new Buffer(0);
}

util.inherits(StreamToBuffer, stream.Transform);

StreamToBuffer.prototype._transform = function(chunk, encoding, callback) {
    this.tailBuffer = Buffer.concat([this.tailBuffer, chunk]); 
    console.log('streamToBuffer');
}

StreamToBuffer.prototype._flush = function(callback) {
    callback();
}

module.exports = StreamToBuffer;

编辑: 在将回调函数传递给StreamToBuffer构造函数后,我发现了一些错误 - 在 _transform()方法中缺少 callback(); 。添加之后,事件'end'监听器至少在标准读取流上工作。

StreamToBuffer.prototype._transform = function(chunk, encoding, callback) {
    this.tailBuffer = Buffer.concat([this.tailBuffer, chunk]); 
    console.log('streamToBuffer');
    callback();
}

另一种方法是将回调函数传递给StreamToBuffer构造函数,然后在 _flush 方法中调用它。这样做的好处是我们可以确保完成转换。

function samplePipe() {
    var streamToBuffer = new StreamToBuffer(processBuffer);
.....
}

function processBuffer(buffer) {
    console.log('processBuffer');
}

StreamToBuffer:

function StreamToBuffer(callback) {
    stream.Transform.call(this);
    this.tailBuffer = new Buffer(0);
    this.finishCallback = callback;
}

util.inherits(StreamToBuffer, stream.Transform);

StreamToBuffer.prototype._transform = function(chunk, encoding, callback) {
    this.tailBuffer = Buffer.concat([this.tailBuffer, chunk]); 
    console.log('streamToBuffer');
    callback();
}

StreamToBuffer.prototype._flush = function(callback) {
    console.log('flushed');
    callback();
    this.finishCallback(this.tailBuffer);
}

module.exports = StreamToBuffer;

虽然我还没有收到任何答复(感谢其他评论),我认为这个问题对于像我这样学习节点的人来说非常有用。如果你知道更好的解决方案,请回答。谢谢。

1 个答案:

答案 0 :(得分:0)

对于可写流,请尝试pageLoadStrategy事件而不是finish事件:

end