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.
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}`);
});
You can download an image from URL in Node.js using Axios (101k ⭐) 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');
Node-fetch (8.4k ⭐) is a light-weight module that brings Fetch API to Node.js. Fetch API is an interface that allows you to make HTTP requests and receive responses from the server. You can use node-fetch to download images, JSON data, HTML pages, and other resources from the web.
// Need to install node-fetch
const fetch = require("node-fetch");
const fs = require("fs");
const path = require("path");
// The URL of the image to download
const imageURL = "https://example.com/image.jpg";
// The path of the directory to save the image
const dirPath = "./images";
// The name of the image file
const fileName = "image.jpg";
// Create the directory if it does not exist
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
// Use fetch to get the image data as a buffer
fetch(imageURL)
.then((response) => response.buffer())
.then((buffer) => {
// Write the buffer to a file
fs.writeFile(path.join(dirPath, fileName), buffer, (err) => {
if (err) {
console.error(err);
} else {
console.log("Image downloaded successfully");
}
});
})
.catch((error) => {
console.error(error);
});