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
gfxmonk's answer has a very tight data race between the callback and the file.close()
completing. file.close()
actually takes a callback that is called when the close has completed. Otherwise, immediate uses of the file may fail (very rarely!).
A complete solution is:
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.
});
});
}
Without waiting for the finish event, naive scripts may end up with an incomplete file. Without scheduling the cb
callback via close, you may get a race between accessing the file and the file actually being ready.