In this tutorial, we will learn how to download and save an image using Node.js. We will use the popular Axios library, which allows us to make HTTP requests.
To begin, make sure you have Axios installed in your project by running the following command:
npm install axios
Once Axios is installed, import it into your project like this:
import axios from 'axios';
Next, let’s create a function called download()
that will handle the actual downloading of the image. This function takes two parameters: the URL of the remote image and the filepath where you want to save the image locally. Here’s the code for the download()
function:
async function download(url, filepath) {
const response = await axios({
url,
method: 'GET',
responseType: 'stream',
});
return new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(filepath))
.on('error', reject)
.once('close', () => resolve(filepath));
});
}
In the download()
function, we first make a GET request using Axios. The responseType: 'stream'
option tells Axios to treat the response as a stream, which is ideal for downloading files.
Then, we create a promise that resolves or rejects based on the result of the download. We use the pipe()
method to pipe the data stream from the HTTP response to a writable stream created using the createWriteStream()
method from the fs module. This allows us to save the downloaded image to the specified local filepath.
Finally, we call the download()
function by providing the remote URL of the image you want to download and the local filepath where you want to save it. Here’s an example:
const remote_url = 'https://...';
const local_path = './images/test.png';
await download(remote_url, local_path);
That’s it! You have successfully downloaded and saved an image using Node.js and Axios.
Please note that you will need to import the fs module (import fs from 'fs';
) at the beginning of your file in order to use the createWriteStream()
method.
Tags: Node.js, Axios, file download, image download, save image