How to download files with Node.js

How to download files with Node.js

In this article, we will walk you through the steps to download a remote file using Node.js.

Node.js is a JavaScript runtime environment that allows developers to build high-performance server-side applications. One of the common operations in Node.js is downloading remote files from the Internet. This can be useful for downloading images, configuration files, documents, or any other type of resource available online. In this article, we will walk you through the steps to download a remote file using Node.js.

It involves redirecting the byte buffer received from a GET request towards a stream that will create the file in the local file system. That is:


'use strict';

const https = require('https');
const fs = require('fs');

const fileUrl = 'https://site.tld/file.pdf'; // Replace with the actual URL of the file
const downloadPath = './file.pdf'; // Specify the path and name of the downloaded file

const fileStream = fs.createWriteStream(downloadPath);

https.get(fileUrl, response => {
   response.pipe(fileStream); // Pipe on the write stream

   fileStream.on('finish', () => {
     fileStream.close();
     console.log(`The file was successfully downloaded to ${downloadPath}`);
   });

}).on('error', err => {
   fs.unlink(downloadPath, () => {}); // Delete the file on error
   console.error(`Error downloading file: ${err.message}`);
});

The remote file will be downloaded to the location specified in the code and you will receive a confirmation in the terminal output.

Now you have a solid foundation for downloading remote files with Node.js. You can expand this code by adding features like error handling or downloading multiple files sequentially. Knowing these techniques is useful for developing applications that require access to external resources on the Internet.