How to download a file using Node.js?


We can download file using Node.js by either using third-party libraries or using some inbuilt packages.

Method 1: Using 'https' and 'fs' module

We can use the http GET method to fetch the files that are to be downloaded.

  • The createWriteStream() method from fs module creates a writable stream and receives the argument with the location of the file where it needs to be saved.

  • pipe() is another method from fs that reads the data from the readable stream and writes it onto the writable stream and file.

Example 1

Create a file with the name downloadFile.js and copy the following code snippet. After creating the file, use the command node downloadFile.js to run this code as shown in the example below −

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

// URL of the image
const url = "https://www.tutorialspoint.com/cg/images/cgbanner.jpg";

https.get(url, (res) => {
   const path = "downloaded-image.jpg";
   const writeStream = fs.createWriteStream(path);

   res.pipe(writeStream);

   writeStream.on("finish", () => {
      writeStream.close();
      console.log("Download Completed!");
   })
})

Output

C:\home
ode>> node downloadFile.js Download Completed!

Method 2: Using 'download' Library

We can use the third-party 'download' library to install its dependency and use it for downloading files.

Installation

npm install download

Example 2

// Download File using 3rd party library

// Importing the download module
const download = require('download');

// Path of the image to be downloaded
const file = '/home/mayankaggarwal/mysql-test/tutorials_point_img.jpg';
// Path to store the downloaded file
const filePath = `${__dirname}/files`;

download(file,filePath)
.then(() => {
   console.log('File downloaded successfully!');
})

Output

C:\home
ode>> node downloadFile.js File downloaded successfully!

Updated on: 17-Jan-2022

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements