How to Download an Image from URL in Node
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:
1 | import os from 'os'; |
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