streams2 Writable - is there a way to define an "_end" function?

131 Views Asked by At

I'm a bit confused about the new streams2 API of node.js. I try to create a Writable stream, but I can't find a way to define a "_end" function. There's only the "_write"-function that I can override. There is also nothing in the docs that would tell me how to do it.

I'm looking for a way to define a function to properly close the stream, after someone calls mystream.end() on it.

My stream writes to another stream and after closing my stream, I also want to close the underlying stream after all the data was sent.

How can I do it?

How it could look like:

var stream = require("stream");

function MyStream(basestream){
    this.base = basestream;
}
MyStream.prototype = Object.create(stream.Writable);
MyStream.prototype._write = function(chunk,encoding,cb){
    this.base.write(chunk,encoding,cb);
}
MyStream.prototype._end = function(cb){
    this.base.end(cb);
}
1

There are 1 best solutions below

0
On BEST ANSWER

You can listen for finish events on your stream and make it call _end:

function MyStream(basestream) {
  stream.Writable.call(this); // I don't think this is strictly necessary in this case, but better be safe :)
  this.base = basestream;
  this.on('finish', this._end.bind(this));
}

MyStream.prototype._end = function(cb){
  this.base.end(cb);
}