Created
June 23, 2017 10:30
-
-
Save barbietunnie/f0e27701651a7f208c79668ce1380ca1 to your computer and use it in GitHub Desktop.
Downloading files in Node.js
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
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