Skip to content

Instantly share code, notes, and snippets.

@robertoentringer
Forked from falkolab/download.js
Created April 18, 2021 20:29
Show Gist options
  • Save robertoentringer/d409ca021182b22a4dcc337a51d0bfb4 to your computer and use it in GitHub Desktop.
Save robertoentringer/d409ca021182b22a4dcc337a51d0bfb4 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