Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Created June 23, 2017 10:30
Show Gist options
  • Save barbietunnie/f0e27701651a7f208c79668ce1380ca1 to your computer and use it in GitHub Desktop.
Save barbietunnie/f0e27701651a7f208c79668ce1380ca1 to your computer and use it in GitHub Desktop.
Downloading files in Node.js
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment