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