This repository has been archived by the owner on Dec 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 179
/
wget.js
61 lines (52 loc) · 1.94 KB
/
wget.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
var url = require('url'),
bytes = require('./bytes'),
fs = require('fs'),
ESC_UP_CLL = '\x1B[1A\x1B[K'; // Up + Clear-Line
function wget(uri, callback) {
console.log('Download file from %s', uri);
var options = url.parse(uri);
var paths = options.pathname.split('/');
var filename = paths[paths.length - 1];
console.log(filename);
var http = require(uri.indexOf('https') === 0 ? 'https' : 'http');
var req = http.get(options, function (res) {
if (res.statusCode === 302 || res.statusCode === 301) {
console.log('Redirect: ' + res.headers.location);
return wget(res.headers.location, callback);
}
if (res.statusCode !== 200) {
callback(null);
return;
}
var contentLength = parseInt(res.headers['content-length'], 10);
if (isNaN(contentLength)) {
console.log('Can\'t get \'content-length\'');
callback(null);
return;
}
console.log('Content length is %s', bytes(contentLength));
var data = new Buffer(contentLength);
var offset = 0;
var start = Date.now();
console.log(''); // New line for ESC_UP_CLL
res.on('data', function (buf) {
buf.copy(data, offset);
offset += buf.length;
var use = Date.now() - start;
if (use === 0) {
use = 1;
}
console.log(ESC_UP_CLL + 'Download %d%, %s / %s, %s/s ...',
parseInt(offset / contentLength * 100, 10), bytes(offset), bytes(contentLength),
bytes(offset / use * 1000));
});
res.on('end', function () {
console.log('Donwload done');
callback(filename, data);
});
});
req.on('error', function (e) {
console.log('Got error: ' + e.message);
});
}
module.exports = wget;