2016-04-04 63 views
0

假设customWS是写流..实现自定义写流类的完成事件处理

util.inherits(customWS, stream.Writable); 

我们实现我们的逻辑来处理在_write()像下面的写..

customWS.prototype._write = function(chunk, encoding, done) { 
    // ... 
    } 

现在要使用customWS类,我们会做类似下面的操作。

aReadableStream.pipe(new customWS()).on('finish', callback); 

那么callback函数的参数是什么?

我可以通过一个像callback ..

function(data) { 
    // ...  
    } 

..或它固定??

如果它不是固定的,那么如何在customWS类中实现这样的回调?

有类似的东西..

// in the implementation of customWS class 
    customWS.prototype._finish = function(user_specified_callback) { 
    user_specified_callback(some_data_say_a_bool_val); 
    } 

    // in the code, where i use the customWS class 
    aReadableStream.pipe(new customWS()).on('finish', function(flag) { 
    if (flag) { 
     console.log('yes'); 
    } 
    }); 

回答

0

通常,您应该不需要做任何事情来支持finish()finish事件及其签名记录在here。它没有任何参数,它只是一个通知,表示可写入的流已经“关闭”并且不能再被写入。

如果作为流实现者,您需要在可写流的“关闭”之前专门做一些事情,那么在撰写本文时,您或多或少会失去运气。有一个PR将此功能添加到可写入的流。如果你正在实现一个Transform流,你将拥有_flush()这就是你想要的,但是这只在你实现一个双工流时才有用(不能只写)。