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
Maybe node.js has changed, but it seems there are some problems with the other solutions (using node v8.1.2):
file.close()
in the finish
event. Per default the fs.createWriteStream
is set to autoClose: https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_optionsfile.close()
should be called on error. Maybe this is not needed when the file is deleted (unlink()
), but normally it is: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_optionsstatusCode !== 200
fs.unlink()
without a callback is deprecated (outputs warning)dest
file exists; it is overriddenBelow is a modified solution (using ES6 and promises) which handles these problems.
const http = require("http");
const fs = require("fs");
function download(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest, { flags: "wx" });
const request = http.get(url, response => {
if (response.statusCode === 200) {
response.pipe(file);
} else {
file.close();
fs.unlink(dest, () => {}); // Delete temp file
reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
}
});
request.on("error", err => {
file.close();
fs.unlink(dest, () => {}); // Delete temp file
reject(err.message);
});
file.on("finish", () => {
resolve();
});
file.on("error", err => {
file.close();
if (err.code === "EEXIST") {
reject("File already exists");
} else {
fs.unlink(dest, () => {}); // Delete temp file
reject(err.message);
}
});
});
}