How do I download a file with Node.js without using third-party libraries?
I don\'t need anything special. I only want to download a file from a giv
As Michelle Tilley said, but with the appropriate control flow:
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
Without waiting for the finish event, naive scripts may end up with an incomplete file.
Edit: Thanks to @Augusto Roman for pointing out that cb should be passed to file.close, not called explicitly.