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.