0

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?

VGR
  • 40,506
  • 4
  • 48
  • 63
  • Are you referring to standard "Basic Auth" (i.e. using your browser *the browser* asks you for credentials in a dedicated dialog) or is it a form-based authentication (*the site* displays a form to enter the credentials in)? – criztovyl Jul 23 '22 at 11:29
  • Great question, I forgot to mention. It is "Basic Auth". Not a form. – Emrik Ahlström Jul 23 '22 at 11:30
  • If this is Basic Auth, this answer might help you out: https://stackoverflow.com/questions/18264601 – Jaxon Crosmas Jul 23 '22 at 11:42

0 Answers0