I have a script that will download a file from a third party URL, to a local folder on my server.
function download(url, dest) {
const fs = require("fs");
const http = require("https");
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);
}
});
});
}
What makes this case different is that this script only downloads from a URL it has public access to. But now I'm trying to download a file from a link that is protected by 2 fields, username and password.
How can I easily implement a header that will include the "username" and "password" into this script when accessing the download URL?