/

How to Download an Image Using Node.js

How to Download an Image Using Node.js

Downloading files from a server programmatically using Node.js can be accomplished by following a simple process. In this blog post, we will explore how to connect to a server, download an image file, and store it locally.

To achieve this, we will be using the fs built-in module and the request module. Please make sure you have the request module installed by running the following command:

1
npm install request

Once you have the request module installed, you can use the following code to download an image:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const fs = require('fs');
const request = require('request');

const download = (url, path, callback) => {
request.head(url, (err, res, body) => {
request(url)
.pipe(fs.createWriteStream(path))
.on('close', callback);
});
};

const url = 'https://…';
const path = './images/image.png';

download(url, path, () => {
console.log('✅ Done!');
});

In the code above, the download function accepts three parameters: the URL of the image you want to download, the local path where you want to save the image, and a callback function to be executed once the download is complete.

First, we send a HTTP HEAD request to the specified URL to check its availability. Once the response is received, we initiate the download by sending a regular HTTP request and piping the response to a write stream created using the fs module. The image will be saved at the specified local path. When the download is finished, the provided callback function will be invoked, and a success message will be logged to the console.

Keep in mind that the request module has been deprecated, which means it will no longer receive new features but only bug fixes. However, it is still perfectly functional and widely used.

Tags: Node.js, file download, server connection, fs module, request module