-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
get.js
69 lines (66 loc) · 1.68 KB
/
get.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
59
60
61
62
63
64
65
66
67
68
69
let https = require('node:https')
let pico = require('picocolors')
let zlib = require('node:zlib')
function showError(url, message) {
process.stderr.write(
'\n' +
pico.red(url) +
'\n' +
pico.bgRed(' Request error ') +
' ' +
message +
'\n'
)
process.exit(1)
}
function download(url, callback, errors = 0) {
function onError(e) {
if (errors > 2) showError(url, e.toString())
process.stderr.write(e.toString() + '\n')
download(url, callback, errors + 1)
}
https
.get(
url,
{
headers: { 'accept-encoding': 'gzip,deflate' }
},
res => {
if (res.statusCode >= 300 && res.statusCode <= 399) {
download(res.headers.location, callback, 0)
} else if (res.statusCode >= 200 && res.statusCode <= 299) {
callback(res)
} else {
showError(url, res.statusCode)
}
res.on('error', onError)
}
)
.on('error', onError)
}
module.exports = async function get(url) {
return new Promise(resolve => {
download(url, res => {
let chunks = []
res.on('data', i => {
chunks.push(i)
})
res.on('end', () => {
let buffer = Buffer.concat(chunks)
if (res.headers['content-encoding'] === 'gzip') {
zlib.gunzip(buffer, (err, decoded) => {
if (err) throw err
resolve(decoded.toString())
})
} else if (res.headers['content-encoding'] === 'deflate') {
zlib.inflate(buffer, (err, decoded) => {
if (err) throw err
resolve(decoded.toString())
})
} else {
resolve(buffer.toString())
}
})
})
})
}