index.js
839 Bytes
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
exports.array = toArray
exports.buffer = toBuffer
function toArray(stream, callback) {
var arr = []
stream.on('data', onData)
stream.once('end', onEnd)
stream.once('error', callback)
stream.once('error', cleanup)
stream.once('close', cleanup)
function onData(doc) {
arr.push(doc)
}
function onEnd() {
callback(null, arr)
cleanup()
}
function cleanup() {
arr = null
stream.removeListener('data', onData)
stream.removeListener('end', onEnd)
stream.removeListener('error', callback)
stream.removeListener('error', cleanup)
stream.removeListener('close', cleanup)
}
return stream
}
function toBuffer(stream, callback) {
toArray(stream, function (err, arr) {
if (err || !arr)
callback(err)
else
callback(null, Buffer.concat(arr))
})
return stream
}