-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient-node.js
More file actions
100 lines (78 loc) · 2.44 KB
/
client-node.js
File metadata and controls
100 lines (78 loc) · 2.44 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { isFormData, isStream, normalizeTrailingSlashInPath } from './utils'
export function sendNodeAPIRequest(path, method, headers, body, encoding, timeout, withCredentials, abortSignal) {
return new Promise((resolve, reject) => {
const u = require('url').parse(path)
const form = isFormData(body) && body
const https = u.protocol === 'https:'
const options = {
signal: abortSignal,
host : u.hostname,
port : u.port || (https ? 443 : 80),
path : normalizeTrailingSlashInPath(path, u) + (u.search || ''),
method,
headers,
timeout,
}
if (typeof withCredentials === 'boolean') {
options.withCredentials = withCredentials
}
const _send = () => {
const Buffer = require('buffer').Buffer
const httpClient = require(https ? 'https' : 'http')
const req = httpClient.request(options, res => {
const strings = []
const buffers = []
let bufferLength = 0
let body = ''
const { statusCode: status, statusMessage: statusText, headers } = res
res.on('data', chunk => {
if (!Buffer.isBuffer(chunk)) {
strings.push(chunk)
} else if (chunk.length) {
bufferLength += chunk.length
buffers.push(chunk)
}
})
res.on('end', () => {
if (bufferLength) {
body = Buffer.concat(buffers, bufferLength)
if (encoding != null) {
body = body.toString(encoding)
}
} else if (strings.length) {
body = strings.join()
}
resolve({ status, statusText, headers, body })
})
res.on('error', reject)
})
req.on('error', reject)
req.on('timeout', () => {
req.destroy(new Error('Connection aborted due to timeout'))
})
if (body) {
if (isStream(body)) {
body.pipe(req)
return
}
req.write(body)
}
req.end()
}
if (form) {
Object.assign(options.headers, form.getHeaders())
form.getLength(function(err, length) {
if (!err && !isNaN(length)) {
options.headers['content-length'] = length
}
_send()
})
} else {
if (body && !options.headers['content-length']) {
const Buffer = require('buffer').Buffer
options.headers['content-length'] = Buffer.byteLength(body)
}
_send()
}
})
}