Skip to content

Instantly share code, notes, and snippets.

@ialpert
Created July 18, 2012 14:43
Show Gist options
  • Save ialpert/3136595 to your computer and use it in GitHub Desktop.
Save ialpert/3136595 to your computer and use it in GitHub Desktop.
Download file using GET and nodejs
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);
});
}
@mikebz
Copy link

mikebz commented Mar 30, 2013

you might want to callback in case of the error too... right now this thing just kinda goes away in case something came up.

@ecdeveloper
Copy link

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;
}

@paulohp
Copy link

paulohp commented Jun 17, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment