3

我对node.js 的新streams2 API 有点困惑。我尝试创建一个可写流,但找不到定义“_end”函数的方法。只有我可以覆盖的“_write”函数。文档中也没有任何内容可以告诉我该怎么做。

在有人调用 mystream.end() 之后,我正在寻找一种方法来定义一个函数以正确关闭流。

我的流写入另一个流,关闭我的流后,我还想在发送所有数据后关闭底层流。

我该怎么做?

它看起来如何:

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

1 回答 1

5

您可以侦听finish流中的事件并使其调用_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);
}
于 2013-04-02T15:37:15.073 回答