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.get(url, (res) => {
   const path = "downloaded-image.jpg";
   const writeStream = fs.createWriteStream(path);


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


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.


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`;

.then(() => {
   console.log('File downloaded successfully!');


ode>> node downloadFile.js File downloaded successfully!