-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode-download.js
35 lines (30 loc) · 884 Bytes
/
node-download.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
const https = require('https');
const fs = require('fs');
module.exports = function download(url, dest, file, callback) {
const request = https.get(url, function(response) {
const {
statusCode,
headers,
} = response;
if (statusCode >= 300 && statusCode < 400 && headers.location) {
const location = headers.location;
download(location, dest, file, callback);
} else {
checkDir(dest,function(err){
if (err) { return callback(err); }
const fileStream = fs.createWriteStream(dest+'/'+file);
response.pipe(fileStream);
fileStream.on('finish', callback).on('error', callback);
});
}
});
request.on('error', callback);
};
function checkDir(path, callback) {
fs.stat(path, function(err, stat) {
if (err) {
return fs.mkdir(path, '777', callback);
}
callback(null);
});
}