-
Notifications
You must be signed in to change notification settings - Fork 21
/
dl.js
43 lines (39 loc) · 1.21 KB
/
dl.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
// https://gist.github.com/falkolab/f160f446d0bda8a69172
const { parse } = require('url')
const http = require('https')
const fs = require('fs')
const { basename } = require('path')
const TIMEOUT = 10000
module.exports = function(url, path) {
const uri = parse(url)
if (!path) {
path = basename(uri.path)
}
const file = fs.createWriteStream(path)
return new Promise(function(resolve, reject) {
const request = http.get(uri.href).on('response', function(res) {
const len = parseInt(res.headers['content-length'], 10)
let downloaded = 0
let percent = 0
res
.on('data', function(chunk) {
file.write(chunk)
downloaded += chunk.length
percent = (100.0 * downloaded / len).toFixed(2)
process.stdout.write(`Downloading base.ipa - ${percent}%\r`)
})
.on('end', function() {
file.end()
console.log(`Downloaded!`)
resolve()
})
.on('error', function (err) {
reject(err)
})
})
request.setTimeout(TIMEOUT, function() {
request.abort()
reject(new Error(`request timeout after ${TIMEOUT / 1000.0}s`))
})
})
}