forked from netlify/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-stream-promise.js
More file actions
49 lines (42 loc) · 1.2 KB
/
Copy pathcreate-stream-promise.js
File metadata and controls
49 lines (42 loc) · 1.2 KB
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
const { Buffer } = require('buffer')
const createStreamPromise = function (stream, timeoutSeconds, bytesLimit = DEFAULT_BYTES_LIMIT) {
return new Promise(function streamPromiseFunc(resolve, reject) {
let data = []
let dataLength = 0
let timeoutId = null
if (timeoutSeconds != null && Number.isFinite(timeoutSeconds)) {
timeoutId = setTimeout(() => {
data = null
reject(new Error('Request timed out waiting for body'))
}, timeoutSeconds * SEC_TO_MILLISEC)
}
stream.on('data', function onData(chunk) {
if (!Array.isArray(data)) {
// Stream harvesting closed
return
}
dataLength += chunk.length
if (dataLength > bytesLimit) {
data = null
reject(new Error('Stream body too big'))
} else {
data.push(chunk)
}
})
stream.on('error', function onError(error) {
data = null
reject(error)
clearTimeout(timeoutId)
})
stream.on('end', function onEnd() {
clearTimeout(timeoutId)
if (data) {
resolve(Buffer.concat(data))
}
})
})
}
const SEC_TO_MILLISEC = 1e3
// 6 MiB
const DEFAULT_BYTES_LIMIT = 6e6
module.exports = { createStreamPromise }