Skip to content

Instantly share code, notes, and snippets.

@brandy
Forked from falkolab/download.js
Created November 26, 2022 23:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandy/25dd4971efeb7428bc14a977e1c13349 to your computer and use it in GitHub Desktop.
Save brandy/25dd4971efeb7428bc14a977e1c13349 to your computer and use it in GitHub Desktop.
Download file by http with progress (NodeJS)
function download(fileUrl, apiPath, callback) {
var url = require('url'),
http = require('http'),
p = url.parse(fileUrl),
timeout = 10000;
var file = fs.createWriteStream(apiPath);
var timeout_wrapper = function( req ) {
return function() {
console.log('abort');
req.abort();
callback("File transfer timeout!");
};
};
console.log('before');
var request = http.get(fileUrl).on('response', function(res) {
console.log('in cb');
var len = parseInt(response.headers['content-length'], 10);
var downloaded = 0;
res.on('data', function(chunk) {
file.write(chunk);
downloaded += chunk.length;
process.stdout.write("Downloading " + (100.0 * downloaded / len).toFixed(2) + "% " + downloaded + " bytes" + isWin ? "\033[0G": "\r");
// reset timeout
clearTimeout( timeoutId );
timeoutId = setTimeout( fn, timeout );
}).on('end', function () {
// clear timeout
clearTimeout( timeoutId );
file.end();
console.log(file_name + ' downloaded to: ' + apiPath);
callback(null);
}).on('error', function (err) {
// clear timeout
clearTimeout( timeoutId );
callback(err.message);
});
});
// generate timeout handler
var fn = timeout_wrapper( request );
// set initial timeout
var timeoutId = setTimeout( fn, timeout );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment