index.js 1011 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. const Minipass = require('minipass')
  2. const _flush = Symbol('_flush')
  3. const _flushed = Symbol('_flushed')
  4. const _flushing = Symbol('_flushing')
  5. class Flush extends Minipass {
  6. constructor (opt = {}) {
  7. if (typeof opt === 'function')
  8. opt = { flush: opt }
  9. super(opt)
  10. // or extend this class and provide a 'flush' method in your subclass
  11. if (typeof opt.flush !== 'function' && typeof this.flush !== 'function')
  12. throw new TypeError('must provide flush function in options')
  13. this[_flush] = opt.flush || this.flush
  14. }
  15. emit (ev, ...data) {
  16. if ((ev !== 'end' && ev !== 'finish') || this[_flushed])
  17. return super.emit(ev, ...data)
  18. if (this[_flushing])
  19. return
  20. this[_flushing] = true
  21. const afterFlush = er => {
  22. this[_flushed] = true
  23. er ? super.emit('error', er) : super.emit('end')
  24. }
  25. const ret = this[_flush](afterFlush)
  26. if (ret && ret.then)
  27. ret.then(() => afterFlush(), er => afterFlush(er))
  28. }
  29. }
  30. module.exports = Flush