Created
July 18, 2012 14:43
-
-
Save ialpert/3136595 to your computer and use it in GitHub Desktop.
Download file using GET and nodejs
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 download(url, cb) { | |
var data = ""; | |
var request = require("http").get(url, function(res) { | |
res.on('data', function(chunk) { | |
data += chunk; | |
}); | |
res.on('end', function() { | |
cb(data); | |
}) | |
}); | |
request.on('error', function(e) { | |
console.log("Got error: " + e.message); | |
}); | |
} |
Also, add a check for res.statusCode. In case it's 301 or 302 (redirect) - make a recursive call of download. Smth like:
if ( [301, 302].indexOf(res.statusCode) > -1 ) {
download(res.headers.location, cb);
return;
}
a more elegant solution:
https://gist.github.com/alanhoff/fe17f8cbc1888110ba33
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you might want to callback in case of the error too... right now this thing just kinda goes away in case something came up.