Created
November 26, 2014 08:38
-
-
Save cdax/5ec05a3be5e163243ebd to your computer and use it in GitHub Desktop.
A simple file download function (supports promises via deferreds)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _http_get(url) { | |
var deferred = Q.defer(); | |
http.get(url, deferred.resolve); | |
return deferred.promise; | |
} | |
function download(url, filepath, progressCallback, callback) { | |
//http.get() promisified using Q.nfcall() | |
return | |
_http_get(url) | |
.then(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() { | |
return filename; | |
}); | |
//Promise rejected | |
res.on('error', function(err) { | |
throw err; | |
}) | |
//Progress callback | |
if(totalLength > 0) { | |
res.on('data', function() { | |
data += chunk.toString(); | |
if(progressCallback === undefined) | |
progressCallback(data.length / totalLength); | |
}); | |
} | |
} | |
}).nodeify(callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment