# How to download a file using Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 28, 2021, updated Aug 9, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-download-file

> Learn how to use the native FS and HTTPS modules to download a file into a local folder using Node.js.

There are multiple ways to download and save a file to the local filesystem in Node.js. You can either use the built-in modules like `fs` and `https` or 3rd party open-source libraries.

## Built-in modules

Node.js provides `fs` and `https` modules that can be used to download a file from an external URL and save it to the local filesystem. The file could be anything: a PDF file, an image, or a simple text file.

The `fs` module grants you access to the filesystem to [read and write files](https://attacomsian.com/blog/reading-writing-files-nodejs) in Node.js. 

Similarly, the `https` module allows you to [make an HTTPS in Node.js](https://attacomsian.com/blog/node-make-http-requests) without using any 3rd-party client.

Here is an example that download a PNG image from one of my websites:

```javascript
const fs = require('fs')
const https = require('https')

// File URL
const url = `https://acquirebase.com/img/logo.png`

// Download the file
https
  .get(url, res => {
    // Open file in local filesystem
    const file = fs.createWriteStream(`logo.png`)

    // Write data into local file
    res.pipe(file)

    // Close the file
    file.on('finish', () => {
      file.close()
      console.log(`File downloaded!`)
    })
  })
  .on('error', err => {
    console.log('Error: ', err.message)
  })
```

## 3rd-party libraries

You can also use the [download](https://www.npmjs.com/package/download) package from the NPM registry if you do not like low-level Node.js modules.

To install the `download` package, run the following command:

```bash
$ npm install download --save
```

The `download` package allows you to download a file from a URL and save it under a folder as shown below:

```javascript
const download = require('download')

// File URL
const url = `https://acquirebase.com/img/logo.png`

// Download the file
;(async () => {
  await download(url, './')
})()
```

You can also download multiple files at once using the `download` package:

```javascript
const download = require('download')

;(async () => {
  await Promise.all([
    `https://acquirebase.com/img/logo.png`, 
    `https://acquirebase.com/img/icon.png`]
    .map(url => download(url, './')))
})()
```

The code above saves both `logo.png` and `icon.png` files to the current directory.
