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 writeStream = fs.createWriteStream(path);

res.pipe(writeStream);

writeStream.on("finish", () => {
writeStream.close();
})
})

## Output

C:\homeode>> node downloadFile.js
Download Completed!

#### Installation

npm install download

## Example 2

// Download File using 3rd party library

const file = '/home/mayankaggarwal/mysql-test/tutorials_point_img.jpg';
const filePath = \${__dirname}/files;

})
C:\homeode>> node downloadFile.js
File downloaded successfully!