Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Created June 11, 2012 16:08
Show Gist options
  • Save piscisaureus/2910892 to your computer and use it in GitHub Desktop.
Save piscisaureus/2910892 to your computer and use it in GitHub Desktop.
var Url = require('url'),
Http = require('http'),
Fs = require('fs');
function download(url, filename, cb) {
var urlObject = Url.parse(url),
file;
var request = Http.get(urlObject, function(res) {
if (res.statusCode != 200) {
makeCallback(new Error("HTTP Error: " + res.statusCode));
return;
}
file = Fs.createWriteStream(filename);
res.pipe(file);
file.on('error', function() {
file.destroy();
});
file.on('close', function() {
file = null;
makeCallback();
});
});
request.on('error', function(err) {
if (file) file.destroy();
makeCallback(err);
});
function makeCallback(err) {
if (!cb) return;
cb(err);
cb = null;
}
}
function test_download(url, filename) {
download(url, filename, function(err) {
console.log("url:", url);
console.log("filename:", filename);
console.log("result", err || 'success');
console.log("");
});
}
// Should succeed:
test_download('http://www.google.com/images/srpr/logo3w.png', 'google.png');
// Should fail with HTTP 4xx or 5xx status
test_download('http://www.google.com/does not exists', 'fail1.png');
// Should fail with a DNS error
test_download('http://324579jhfsdlflkdsf/', 'fail2.png');
// Should fail with an ECONNREFUSED or ETIMEDOUT error
test_download('http://www.google.com:9876/test.png', 'fail3.png');
// Should fail with an ECONNREFUSED or ETIMEDOUT error
test_download('http://www.c9.io:81/test.png', 'fail4.png');
// Should fail with ENOENT because the target filename is invalid
test_download('http://www.google.com/images/srpr/logo3w.png', '');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment