You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var stream = require('readable-stream')
  2. var inherits = require('inherits')
  3. var SIGNAL_FLUSH =(Buffer.from && Buffer.from !== Uint8Array.from)
  4. ? Buffer.from([0])
  5. : new Buffer([0])
  6. module.exports = WriteStream
  7. function WriteStream (opts, write, flush) {
  8. if (!(this instanceof WriteStream)) return new WriteStream(opts, write, flush)
  9. if (typeof opts === 'function') {
  10. flush = write
  11. write = opts
  12. opts = {}
  13. }
  14. stream.Writable.call(this, opts)
  15. this.destroyed = false
  16. this._worker = write || null
  17. this._flush = flush || null
  18. }
  19. inherits(WriteStream, stream.Writable)
  20. WriteStream.obj = function (opts, worker, flush) {
  21. if (typeof opts === 'function') return WriteStream.obj(null, opts, worker)
  22. if (!opts) opts = {}
  23. opts.objectMode = true
  24. return new WriteStream(opts, worker, flush)
  25. }
  26. WriteStream.prototype._write = function (data, enc, cb) {
  27. if (SIGNAL_FLUSH === data) this._flush(cb)
  28. else this._worker(data, enc, cb)
  29. }
  30. WriteStream.prototype.end = function (data, enc, cb) {
  31. if (!this._flush) return stream.Writable.prototype.end.apply(this, arguments)
  32. if (typeof data === 'function') return this.end(null, null, data)
  33. if (typeof enc === 'function') return this.end(data, null, enc)
  34. if (data) this.write(data)
  35. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  36. return stream.Writable.prototype.end.call(this, cb)
  37. }
  38. WriteStream.prototype.destroy = function (err) {
  39. if (this.destroyed) return
  40. this.destroyed = true
  41. if (err) this.emit('error', err)
  42. this.emit('close')
  43. }