FlushWritable.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. * FlushWritable
  3. * Copyright 2014 Tom Frost
  4. */
  5. var EventEmitter = require('events').EventEmitter,
  6. Writable = require('stream').Writable,
  7. util = require('util');
  8. /**
  9. * FlushWritable is a drop-in replacement for stream.Writable that implements
  10. * the Transform stream's _flush() method. FlushWritable is meant to be
  11. * extended, just like stream.Writable. However, in the child class's
  12. * prototype, a method called _flush(cb) can be defined that will halt the
  13. * firing of the 'finish' event until the callback is called. If the callback
  14. * if called with a truthy first argument, 'error' is emitted instead.
  15. * @param {Object} [opts] Options to configure this Writable stream. See the
  16. * Node.js docs for stream.Writable.
  17. * @constructor
  18. */
  19. function FlushWritable(opts) {
  20. Writable.call(this, opts);
  21. }
  22. util.inherits(FlushWritable, Writable);
  23. FlushWritable.prototype.emit = function(evt) {
  24. if (evt === 'finish' && this._flush && !Writable.prototype._flush) {
  25. this._flush(function(err) {
  26. if (err)
  27. EventEmitter.prototype.emit.call(this, 'error', err);
  28. else
  29. EventEmitter.prototype.emit.call(this, 'finish');
  30. }.bind(this));
  31. }
  32. else {
  33. var args = Array.prototype.slice.call(arguments);
  34. EventEmitter.prototype.emit.apply(this, args);
  35. }
  36. };
  37. module.exports = FlushWritable;