heyujie
2021-05-24 4885600ecc369aa2e30a65de8dd7a410f13c34df
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict'
 
var Writable = require('readable-stream').Writable
var inherits = require('inherits')
 
function CallbackStream (options, callback) {
  if (!(this instanceof CallbackStream)) {
    return new CallbackStream(options, callback)
  }
 
  if (typeof options === 'function') {
    callback = options
    options = {}
  }
 
  Writable.call(this, options)
 
  this.results = []
  this.callback = callback
 
  this.on('finish', deliversCallback)
  this.once('pipe', handlePipe)
}
 
function deliversCallback () {
  this.callback(null, this.results)
}
 
function handlePipe (source) {
  source.on('error', this.callback)
}
 
inherits(CallbackStream, Writable)
 
CallbackStream.prototype._write = function (data, encoding, done) {
  this.results.push(data)
  done()
}
 
CallbackStream.obj = function (options, callback) {
  if (typeof options === 'function') {
    callback = options
    options = {}
  }
 
  options.objectMode = true
 
  return new CallbackStream(options, callback)
}
 
module.exports = CallbackStream