Skip to content

Instantly share code, notes, and snippets.

@cdax
Last active August 29, 2015 14:10
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/94b2c1c9f1cb225f8c4b to your computer and use it in GitHub Desktop.
Save cdax/94b2c1c9f1cb225f8c4b to your computer and use it in GitHub Desktop.
A simple file downlaod function (supports promises via deferred)
function download(url, filepath, progressCallback, callback) {
//The deferred object
var deferred = Q.defer();
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, returning the promise
return download(getHeader(res, 'location'), filepath, progressCallback, callback);
} else {
var data = '', totalLength = parseInt(res.getHeader('content-length'));
var file = fs.createWriteStream(filepath);
res.pipe(file);
//Promise fulfilled
res.on('end', function() {
deferred.resolve(filename);
});
//Promise rejected
res.on('error', function(err) {
deferred.reject(err);
})
//Progress callback
if(totalLength > 0) {
res.on('data', function() {
data += chunk.toString();
if(progressCallback === undefined)
progressCallback(data.length / totalLength);
else
//Notifying progress updates using the Promise's progress events
deferred.notify(data.length / totalLength);
});
}
}
});
//Register a callback if supplied
deferred.promise.nodeify(callback);
//Finally, return the promise
return deferred.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment