-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (49 loc) · 1.3 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module.exports = (res, cb) => {
const parent = {
write: res.write,
end: res.end,
content: undefined,
ended: false
}
res.write = function (content) {
accumulate(parent, content)
return parent.write.apply(res, arguments)
}
res.end = function (content, encoding) {
if (!parent.ended) {
parent.ended = true
accumulate(parent, content)
const headers = res.getHeaders()
const payload = map(res.statusCode, headers, parent.content, encoding)
setImmediate(() => {
cb(payload)
})
}
return parent.end.apply(res, arguments)
}
}
function map (status, headers, data, encoding) {
return {
status,
headers,
data,
encoding: typeof encoding === 'string' ? encoding : null
}
}
function accumulate (parent, content) {
if (content) {
if (typeof content === 'string') {
parent.content = (parent.content || '') + content
} else if (Buffer.isBuffer(content)) {
let oldContent = parent.content
if (typeof oldContent === 'string') {
oldContent = Buffer.from(oldContent)
} else if (!oldContent) {
oldContent = Buffer.alloc(0)
}
parent.content = Buffer.concat([oldContent, content], oldContent.length + content.length)
} else {
parent.content = content
}
}
}