How to download an image from URL in Node.js

Mar 16, 2023#node#snippets

Downloading an image from a URL refers to the process of obtaining an image file stored on a remote server and saving it on a local device. This is a common task for many Node.js applications.

In general, downloading an image from a URL involves sending a request to the server that hosts the image, receiving the response containing the binary data of the file, and then writing that data to a file.

Using built-in https

In Node.js, you can download an image from a URL using the built-in http or https module and the fs (file system) module. Here is an example code snippet to download an image from a URL:

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

const imageUrl = 'https://example.com/image.jpg';
const imageName = 'image.jpg';

const file = fs.createWriteStream(imageName);

https.get(imageUrl, response => {
  response.pipe(file);

  file.on('finish', () => {
    file.close();
    console.log(`Image downloaded as ${imageName}`);
  });
}).on('error', err => {
  fs.unlink(imageName);
  console.error(`Error downloading image: ${err.message}`);
});

Using Axios

You can download an image from URL in Node.js using Axios by making a GET request to the image URL and writing the response data to a file using the fs module’s writeFile method. Here’s an example code snippet:

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

async function downloadImage(url, filename) {
  const response = await axios.get(url, { responseType: 'arraybuffer' });

  fs.writeFile(filename, response.data, (err) => {
    if (err) throw err;
    console.log('Image downloaded successfully!');
  });
}

downloadImage('https://example.com/image.jpg', 'image.jpg');