Skip to content

Instantly share code, notes, and snippets.

@cdax
Created November 26, 2014 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdax/65cf487a39b784f72465 to your computer and use it in GitHub Desktop.
Save cdax/65cf487a39b784f72465 to your computer and use it in GitHub Desktop.
A simple file download function in Node.js (supports callbacks only)
function downlaod(url, filepath, progressCallback, callback) {
http.get(url, function(res) {
//Detecting a redirect the way request/request.js does it
if(res.statusCode >= 300 && res.statusCode < 400 && hasHeader(res, 'location')) {
//Get the new URL and make a fresh call to download
download(getHeader(res, 'location'), filepath, progressCallback, callback);
} else {
var data = '', totalLength = parseInt(res.getHeader('content-length'));
var file = fs.createWriteStream(filepath);
res.pipe(file);
//Success callback
res.on('end', function() {
callback(null, filename);
});
//Error callback
res.on('error', function(err) {
callback(err, null);
})
//Progress callback
if(totalLength > 0) {
res.on('data', function() {
data += chunk.toString();
progressCallback(data.length / totalLength);
});
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment