2013-04-02 49 views
3

我對node.js的新streams2 API有些困惑。我嘗試創建一個Writable流,但我找不到定義「_end」函數的方法。只有「_write」功能可以覆蓋。文檔中也沒有任何內容會告訴我如何去做。streams2可寫 - 是否有定義「_end」函數的方法?

我正在尋找一種方法來定義一個函數,以正確地關閉流後,有人在它上面調用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); 
} 

回答

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); 
} 
相關問題