0

There is a file that is offloaded on to a website that now I may need to download back to our own website. It is available as http://www.example.com/uploads/file.xyz.

If you entered the URL in the browser, the download dialog would appear. What I need to do is download that file programmatically using node js (and express) to a folder in my node js express server.

I've seen plenty of examples of using res.download() method but that is not the same. I believe it launches a download dialog. I need to save the file to a directory I choose programmatically, without a dialog.

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

1 Answers1

1

you can download files with writable stream.

Here is an example

import fs from "fs";
import https from "https";

const fileUrl = "https://filesamples.com/samples/document/doc/sample2.doc";

const file = fs.createWriteStream(process.cwd() + "/saved-file.doc");

const request = https.get(fileUrl, (response) => {
  response.pipe(file);
});

request.on("error", (err: Error) => {
  console.error(err);
});

file.on("finish", () => {
  console.log(`File downloaded`);
});

file.on("error", (err: Error) => {
  console.error(`Error while downloading file: ${err.message}`);
});
Taha Ergun
  • 566
  • 2
  • 7
  • 17