Event listener when the transformation of the stream is finished, Node.js -
i trying register event listener @ end of data in pipe transformation. trying register event streams in pipe:
a) custom transform stream (streamtobuffer)
b) standard file read stream
c) standard gunzip stream.
but unfortunately, none of them works (see code below). far try, 'data' event works, not help.
what need continue processing of tailbuffer in streamtobuffer class after transformation finished.
can suggest how achive this?
the code (simplified brevity):
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;
edited: after playing little passing callback function streamtobuffer constructor, have discovered mistake - missing callback(); in _transform() method. after adding it, event 'end' listener works, @ least on standard read stream.
streamtobuffer.prototype._transform = function(chunk, encoding, callback) { this.tailbuffer = buffer.concat([this.tailbuffer, chunk]); console.log('streamtobuffer'); callback(); }
another way pass callback function streamtobuffer constructor , call in _flush method. has advantage can sure transformation completed.
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;
although did not receive answer yet (thanks other comments, anyway), think question can useful people me, learning node. if know better solution, pls answer. thank you.
Comments
Post a Comment