-
Notifications
You must be signed in to change notification settings - Fork 1
/
req.js
58 lines (46 loc) · 1.32 KB
/
req.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
const http = require("http");
const https = require("https");
function req(url, options = {}) {
let parsed = new URL(url);
if (options.json) {
if (!options.headers["content-type"])
options.headers["content-type"] = "application/json";
options.json = JSON.stringify(options.json);
if (!options.headers["content-length"])
options.headers["content-length"] = Buffer.byteLength(options.json);
} else if (options.data) {
if (!options.headers["content-length"])
options.headers["content-length"] = Buffer.byteLength(options.data);
}
return new Promise((resolve, reject) => {
let r = (url.startsWith("https:") ? https : http).request(
url,
options,
(resp) => {
let str = "";
let json = null;
resp.on("data", (chunk) => {
str += chunk;
});
resp.on("end", () => {
try {
json = JSON.parse(str);
} catch (err) {
json = false;
}
const rsv = {
...resp,
headers: resp.headers,
status: resp.statusCode,
data: json || str,
};
resolve(rsv);
});
}
);
if (options.json) r.write(options.json);
else if (options.data) r.write(options.data);
r.end();
});
}
module.exports = req;