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:
-
Import the required modules:
os
,fs
, andhttps
. -
Create an
async
function nameddownloadFileFromURL
that takes the URL of the image and the file location as parameters. -
Inside the function, return a new
Promise
that resolves or rejects based on the success or failure of the download. -
Use the
https.get()
method to make a GET request to the specified URL. -
Check the response status code. If it is greater than or equal to 400, reject the promise with an error containing the status message.
-
Handle redirects by checking if the response code is between 300 and 400 and if there is a
location
header. If so, call thedownloadFile()
function recursively with the new location. -
Create a writable stream using
fs.createWriteStream()
to save the file at the specified file location. -
Use
response.pipe()
to pipe the response data to the fileWriter. -
Finally, resolve the promise with the file location and the
content-type
header of the response. -
In your main code, provide the image URL and the desired file location.
-
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