Download and save a file in Node.js

Reading Time: < 1 minutes

Overview

Download a file in Node.js is pretty straightforward but we have to have into account a couple of things.

  • We are going to make a request and the file will be received in chunks
  • Depending on the size of the file we can do it sync or async with advantages and disadvantages
  • We may require authorization

The code

The following code downloads an image from a given URL and stores it in a given path.

      
const https = require('https');
const fs = require('fs');

/**
 *
 * @param url - the url where we have our file
 * @param fileFullPath - the full file path where we want to store our image
 * @return {Promise<>}
 */
const downloadFile = async (url, fileFullPath) =>{
    console.info('downloading file from url: '+url)
    return new Promise((resolve, reject) => {
        https.get(url, (resp) => {

            // chunk received from the server
            resp.on('data', (chunk) => {
                fs.appendFileSync(fileFullPath, chunk);
            });

            // last chunk received, we are done
            resp.on('end', () => {
                resolve('File downloaded and stored at: '+fileFullPath);
            });

        }).on("error", (err) => {
            reject(new Error(err.message))
        });
    })
}

const url = 'https://i.imgur.com/wgPdAB6.jpeg';
const fileFullPath = '/Users/andrescanavesi/Downloads/test.jpeg';

downloadFile(url, fileFullPath)
    .then(res => console.log(res))
    .catch(err => console.log(err));

// to execute this file type:
// node index.js

      
    

Photo by JF Martin on Unsplash

, , ,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: