【问题标题】:streams2 Writable - is there a way to define an "_end" function?stream2 可写 - 有没有办法定义一个“_end”函数?
【发布时间】:2013-04-02 14:17:46
【问题描述】:

我对 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);
}

【问题讨论】:

    标签: javascript node.js streams2


    【解决方案1】:

    您可以在流中侦听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);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 2015-03-11
      • 1970-01-01
      • 2021-08-15
      相关资源
      最近更新 更多