node.jswritable

Implement finish event handler of custom writable stream class


Assume that customWS is a writable stream ..

  util.inherits(customWS, stream.Writable);

we implement our logic to handle the writes in the _write() like below ..

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

now to use the customWS class, we would do something like below ..

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

so what are the parameters of the callback function ??

can i pass a callback like ..

  function(data) {
    // ...    
  }

.. or is it fixed ??

if it's not fixed then how to implement such callback in the customWS class ??

is there anything like ..

  // 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');
    }
  });

Solution

  • You typically shouldn't need to do anything to support finish(). The finish event and its signature is documented here. It does not have any parameters, it's merely a notification that the writable stream has "closed" and cannot be written to anymore.

    If as the stream implementor you need to specifically do something right before the "closing" of the writable stream, you are more or less out of luck as of this writing. There is a PR to add this functionality to Writable streams. If you were implementing a Transform stream, you'd have _flush() which is what you'd want, but that's only useful if you're implementing a duplex stream (not Writable only).