How to download a file with node.js using https?

Member

by lew , in category: Third Party Scripts , a month ago

How to download a file with node.js using https?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , a month ago

@lew 

To download a file with Node.js using HTTPS, you can use the https module which comes with Node.js by default. Below is an example code to download a file from a given URL using HTTPS:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const https = require('https');
const fs = require('fs');

const fileUrl = 'https://example.com/file-to-download.extension';
const destinationPath = 'downloaded-file.extension';

const file = fs.createWriteStream(destinationPath);

https.get(fileUrl, function(response) {
  response.pipe(file);
  file.on('finish', function() {
    file.close(() => {
      console.log('File downloaded successfully!');
    });
  });
}).on('error', function(err) {
  fs.unlink(destinationPath);
  console.error(err);
});


Replace fileUrl with the URL of the file you want to download and destinationPath with the path where you want to save the file. After running this script, the file will be downloaded to the specified destination path.