How to download a file 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 in Node.js.

Similarly, the https module allows you to make an HTTPS in Node.js without using any 3rd-party client.

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

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 package from the NPM registry if you do not like low-level Node.js modules.

To install the download package, run the following command:

$ 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:

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:

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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.