-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.js
54 lines (46 loc) · 1.33 KB
/
run.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
var http = require('needle');
var fs = require('graceful-fs');
var cheerio = require('cheerio');
var progbar = require('progbar');
http.get('http://datos.gob.cl/dataset/registros-de-importacion-2016', function (err, res) {
var $ = cheerio.load(res.body);
var links = $('.resource-list > li:nth-child(n + 3) > div > ul > li:nth-child(2) > a').map(function (link) {
return $(this).attr('href');
}).get();
var size = 5*1024*1024;
var prevText = '';
function downloadNextFile (retryLink) {
if (!links.length) {
console.error('ALVARUNA!!!!!');
return;
}
var link;
if (retryLink) {
link = retryLink;
} else {
link = links.pop();
}
var fileName = link.replace(/.*\/download\//gi, '');
var out = fs.createWriteStream('downloads/' + fileName);
var bar = new progbar.ProgressBar({
filename: fileName,
size: size
});
http.get(link).on('data', function (chunk) {
bar.advance(chunk.length);
}).on('end', function (err) {
if (err) {
console.log('Error, retrying in 5 seconds');
setTimeout(function () {
downloadNextFile(link);
}, 5000);
} else {
bar.end();
downloadNextFile();
}
}).pipe(out).on('finish', function () {
console.log('Write complete.');
});
}
downloadNextFile();
});