-
Notifications
You must be signed in to change notification settings - Fork 1
/
sink.js
52 lines (45 loc) · 1.3 KB
/
sink.js
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
52
'use strict'
const Stream = require('stream')
const Writable = Stream.Writable
const WritableState = Writable.WritableState
const EventEmitter = require('events').EventEmitter
module.exports = Sink
function Sink (options) {
let _resolve, _reject
const sink = new Promise((resolve, reject) => {
_resolve = resolve
_reject = reject
})
if (typeof options !== 'object') {
options = { objectMode: Boolean(options) }
}
mixinMethods(sink, Writable.prototype)
mixinMethods(sink, EventEmitter.prototype)
WritableCtor.call(sink, {objectMode: Boolean(options.objectMode)})
const accumulator = []
sink._write = (chunk, encoding, written) => {
accumulator.push(chunk)
written()
}
sink.on('finish', () => _resolve(options.objectMode ? accumulator : accumulator.join('')))
sink.on('error', _reject)
if (options.upstreamError) {
sink.on('pipe', (source) => {
source.on('error', _reject)
})
}
return sink
}
Sink.object = function (options) {
return Sink(Object.assign({}, options, { objectMode: true }))
}
function mixinMethods (sink, prototype) {
Object.keys(prototype).forEach(method => {
sink[method] = prototype[method]
})
}
function WritableCtor (options) {
this._writableState = new WritableState(options, this)
this.writable = true
Stream.call(this)
}