-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
49 lines (39 loc) · 1.27 KB
/
app.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
const request = require('request'),
fs = require('fs'),
_cliProgress = require('cli-progress');
const download = (url, filename, callback) => {
const progressBar = new _cliProgress.SingleBar({
format: '{bar} {percentage}% | ETA: {eta}s'
}, _cliProgress.Presets.shades_classic);
const file = fs.createWriteStream(filename);
let receivedBytes = 0
request.get(url)
.on('response', (response) => {
if (response.statusCode !== 200) {
return callback('Response status was ' + response.statusCode);
}
const totalBytes = response.headers['content-length'];
progressBar.start(totalBytes, 0);
})
.on('data', (chunk) => {
receivedBytes += chunk.length;
progressBar.update(receivedBytes);
})
.pipe(file)
.on('error', (err) => {
fs.unlink(filename);
progressBar.stop();
return callback(err.message);
});
file.on('finish', () => {
progressBar.stop();
file.close(callback);
});
file.on('error', (err) => {
fs.unlink(filename);
progressBar.stop();
return callback(err.message);
});
}
const fileUrl = `https://unsplash.com/photos/FHo4labMPSQ/download`;
download(fileUrl, 'knot.jpg', () => {});