Skip to content

Instantly share code, notes, and snippets.

@popomore
Created July 29, 2013 13:59
Show Gist options
  • Save popomore/6104475 to your computer and use it in GitHub Desktop.
Save popomore/6104475 to your computer and use it in GitHub Desktop.
simple download
var fs = require('fs');
var path = require('path');
var url = require('url');
var protocol = {
https: require('https'),
http: require('http')
};
function download(src, dest, cb) {
var options = url.parse(src);
options.agent = false;
var request = protocol[options.protocol.replace(':', '')].request;
var req = request(options, function(res) {
if (res.statusCode === 200) {
res.pipe(fs.createWriteStream(dest));
cb();
} else if (res.statusCode === 302) {
if (res.headers.location) {
download(res.headers.location, dest, cb);
} else {
cb('no location');
}
} else if (res.statusCode === 404) {
cb(404);
} else {
cb(res.statusCode);
}
});
req.on('error', function(err) {
cb(err);
});
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment