-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
39 lines (29 loc) · 902 Bytes
/
index.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
'use strict'
const toArray = require('stream-to-array')
const Promise = require('any-promise')
const onEnd = require('end-of-stream')
module.exports = streamToPromise
async function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
}
async function fromReadable (stream) {
const promise = toArray(stream)
// Ensure stream is in flowing mode
if (stream.resume) stream.resume()
const parts = await promise
if (stream._readableState && stream._readableState.objectMode) {
return parts
}
return Buffer.concat(parts.map(bufferize))
}
async function fromWritable (stream) {
return new Promise(function (resolve, reject) {
onEnd(stream, function (err) {
(err ? reject : resolve)(err)
})
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
}