Downloading multiple images in Node.js can be efficiently accomplished using the Promise and async/await features.
In this article, we are going to look at how to achieve this in your Node.js projects.
To begin, ensure that you have Node.js installed on your system. Then, follow these steps to set up your project:
Create a new directory for your project.
Open a terminal and navigate to the project directory.
Run the following command to initialize a new Node.js project:
npm init -y
Install the required dependencies by running the following command:
npm install request fs
To download multiple images in Node.js, follow these steps:
Create a file named imageDownloader.js
in your project directory.
Open the file and add the following code:
const request = require('request');
const fs = require('fs');
function downloadImage(url, destination) {
request(url)
.pipe(fs.createWriteStream(destination))
.on('close', () => {
console.log('Image downloaded successfully!');
})
.on('error', (err) => {
console.error('Error downloading the image:', err);
});
}
module.exports = downloadImage;
In your main file (e.g., app.js
), import the downloadImage
function and define an array of image URLs.
const downloadImage = require('./imageDownloader');
const imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
];
// Call the downloadImages function
downloadImages();
Implement the downloadImages
function using the async/await approach.
async function downloadImages() {
try {
const downloadPromises = imageUrls.map((url, index) => {
const destination = `./images/image${index + 1}.jpg`;
return downloadImage(url, destination);
});
await Promise.all(downloadPromises);
console.log('All images downloaded successfully!');
} catch (err) {
console.error('Error downloading images:', err);
}
}
At the end of testing the code out, you should get something like this:
๐ก
Make sure to create the folder that you intend to store the image so that, the image will be downloaded to that folder.
Handling errors during the image download process is crucial for a smooth user experience.
By attaching an event listener to the error
event, you can handle errors effectively. In the imageDownloader.js
file, we already handle errors using the on('error')
event listener.
Before downloading images, itโs important to validate the image URLs to avoid unnecessary requests and handle invalid URLs.
Read on: How to Check if an Image URL is Valid in JavaScript?
You can utilize regular expressions or libraries like url-regex
to validate URLs. The url-regex library provides a simple way to validate URLs.