How to use the http or https Module In NodeJS
Node.js has built-in modules like ‘https’ and ‘http’ for making HTTP requests. You can utilize these modules to download files from a remote server. The GET method is used on HTTPS to retrieve the file to be downloaded. The ‘createWriteStream()’ method is used to create a writable stream and takes only one argument, which is the location where the file is to be saved. Additionally, the ‘pipe()’ method reads the data from the readable stream and writes it to the writable stream.
Example: Implementation to show how to download files using an HTTP module.
const http = require('http');
const fs = require('fs');
const fileUrl = 'http://example.com/file.txt';
const destination = 'downloaded_file.txt';
const file = fs.createWriteStream(destination);
http.get(fileUrl, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close(() => {
console.log('File downloaded successfully');
});
});
}).on('error', (err) => {
fs.unlink(destination, () => {
console.error('Error downloading file:', err);
});
});
Step to Run Application: Run the application using the following command from the root directory of the project
node .\app.js
How to Download a File Using Node.js?
Downloading files from the internet is a common task in many Node.js applications, whether it’s fetching images, videos, documents, or any other type of file. In this article, we’ll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.
Using Built-in Modules
Table of Content
- Using the http or https Module
- Using third party libraries
- Using download Library