@jnode/request 1.0.1 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.js +10 -3
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -7,14 +7,21 @@ Simple HTTP(s) package for Node.js.
|
|
|
7
7
|
by JustNode Dev Team / JustApple
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
//load node packages
|
|
11
|
+
const http = require('http');
|
|
12
|
+
const https = require('https');
|
|
13
|
+
|
|
10
14
|
//https request in async/await
|
|
11
15
|
function request(method, url, headers = {}, body) {
|
|
12
16
|
return new Promise((resolve, reject) => {
|
|
13
17
|
//auto provide `Content-Length` header
|
|
14
18
|
headers['Content-Length'] = headers['Content-Length'] ?? (body ? Buffer.byteLength(body) : 0);
|
|
15
19
|
|
|
20
|
+
//support http and https
|
|
21
|
+
const protocol = url.startsWith('https://') ? https : http;
|
|
22
|
+
|
|
16
23
|
//make request
|
|
17
|
-
|
|
24
|
+
protocol.request(url, {
|
|
18
25
|
method: method,
|
|
19
26
|
headers: headers
|
|
20
27
|
}, (res) => {
|
|
@@ -58,13 +65,13 @@ class RequestResponse {
|
|
|
58
65
|
|
|
59
66
|
//to string
|
|
60
67
|
text(encoding) {
|
|
61
|
-
return this.body.toString(encoding);
|
|
68
|
+
return this._text ?? (this._text = this.body.toString(encoding));
|
|
62
69
|
}
|
|
63
70
|
|
|
64
71
|
//to json
|
|
65
72
|
json(encoding) {
|
|
66
73
|
try {
|
|
67
|
-
return JSON.parse(this.body);
|
|
74
|
+
return this._json ?? (this._json = JSON.parse(this.body));
|
|
68
75
|
} catch (err) {
|
|
69
76
|
return undefined;
|
|
70
77
|
}
|