In this tutorial, we will learn how to download an image from a URL in Node.js. We will use the built-in https module and fs module for handling file operations.

Here is the code to accomplish this task:

import os from 'os';
import fs from 'fs';
import https from 'https';

async function downloadFileFromURL(url, fileLocation) {
  return await new Promise((resolve, reject) => {
    https.get(url, (response) => {
      const code = response.statusCode ?? 0;

      if (code >= 400) {
        return reject(new Error(response.statusMessage));
      }

      // Handle redirects
      if (code > 300 && code < 400 && !!response.headers.location) {
        return await downloadFile(response.headers.location);
      }

      // Save the file to disk
      const fileWriter = fs.createWriteStream(fileLocation).on('finish', () => {
        resolve({
          fileLocation,
          contentType: response.headers['content-type'],
        });
      });

      response.pipe(fileWriter);
    }).on('error', (error) => {
      reject(error);
    });
  });
}

const imageUrl = 'https://.... bla bla';
const fileLocation = os.tmpdir() + '/' + rnd(10, rnd.alphaLower);

await downloadFileFromURL(imageUrl, fileLocation);

To download an image from a URL in Node.js, follow these steps:

  1. Import the required modules: os, fs, and https.

  2. Create an async function named downloadFileFromURL that takes the URL of the image and the file location as parameters.

  3. Inside the function, return a new Promise that resolves or rejects based on the success or failure of the download.

  4. Use the https.get() method to make a GET request to the specified URL.

  5. Check the response status code. If it is greater than or equal to 400, reject the promise with an error containing the status message.

  6. Handle redirects by checking if the response code is between 300 and 400 and if there is a location header. If so, call the downloadFile() function recursively with the new location.

  7. Create a writable stream using fs.createWriteStream() to save the file at the specified file location.

  8. Use response.pipe() to pipe the response data to the fileWriter.

  9. Finally, resolve the promise with the file location and the content-type header of the response.

  10. In your main code, provide the image URL and the desired file location.

  11. Call the downloadFileFromURL() function and await its completion.

This way, you can easily download an image from a URL in Node.js.

Tags: Node.js, image download, file operations