-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathget-json.js
More file actions
30 lines (25 loc) · 620 Bytes
/
get-json.js
File metadata and controls
30 lines (25 loc) · 620 Bytes
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
'use strict';
const http = require('node:http');
module.exports = (url) => new Promise((resolve, reject) => {
http.get(url, (res) => {
const code = res.statusCode;
if (code !== 200) {
reject(new Error(`HTTP status code ${code}`));
return;
}
res.on('error', reject);
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const json = Buffer.concat(chunks).toString();
try {
const object = JSON.parse(json);
resolve(object);
} catch (error) {
reject(error);
}
});
});
});