-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdl.js
52 lines (42 loc) · 1.35 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
44
45
46
47
48
49
50
51
52
var dl = (path, targetFile) => {
var http = require('./http'),
chalk = require('chalk'),
ProgressBar = require('progress'),
fs = require('fs'),
url = require('url'),
parsedPath = url.parse(path),
req = http(path).request({
hostname: parsedPath.hostname,
path: parsedPath.pathname,
}),
defer;
defer = new Promise((resolve, reject) => {
req.on('response', function(res) {
var len = parseInt(res.headers['content-length'], 10),
file;
if (res.headers['location']) {
return dl(res.headers['location'], targetFile).then(() => {
resolve();
});
}
file = fs.createWriteStream(targetFile);
console.log('downloading ' + chalk.cyan(path) + ' ..');
var bar = new ProgressBar(' :percent [:bar] eta :etas', {
width: 40,
total: len
});
res.on('data', function (chunk) {
file.write(chunk);
bar.tick(chunk.length);
});
res.on('end', function () {
file.end();
console.log('\n');
resolve();
});
});
req.end();
});
return defer;
}
module.exports = dl;