What is the best way to download a file with Node.js without using third-party libraries?
I need to download a file from a given URL and save it to a specific directory using Node.js, but I want to do it without relying on third-party libraries.
What are the built-in methods for handling nodejs download file, and how can I implement them efficiently?
you can use the https module allows you to send requests to download files, and the fs module allows you to save the file to your system. Using streams ensures that the file is downloaded efficiently without loading the entire file into memory.
const https = require('https');
const fs = require('fs');
const url = 'https://example.com/path/to/file.jpg';
const filePath = './downloaded-file.jpg';
https.get(url, (response) => {
const fileStream = fs.createWriteStream(filePath);
response.pipe(fileStream);
fileStream.on('finish', () => {
console.log('File downloaded successfully!');
});
}).on('error', (err) => {
console.error('Error downloading the file:', err.message);
});
Just to add to @smrity.maharishsarin said, if the URL uses HTTP instead of HTTPS, you can use the http module in a similar way to download the file.
const http = require('http');
const fs = require('fs');
const url = 'http://example.com/path/to/file.jpg';
const filePath = './downloaded-file.jpg';
http.get(url, (response) => {
const fileStream = fs.createWriteStream(filePath);
response.pipe(fileStream);
fileStream.on('finish', () => {
console.log('File downloaded successfully!');
});
}).on('error', (err) => {
console.error('Error downloading the file:', err.message);
});
Handling both HTTP and HTTPS with a Unified Approach totally agree with @akanshasrivastava.1121 @smrity.maharishsarin
You can create a function that works with both http and https by checking the protocol in the URL.
const http = require('http');
const https = require('https');
const fs = require('fs');
const url = require('url');
const filePath = './downloaded-file.jpg';
function downloadFile(fileUrl, dest) {
const parsedUrl = url.parse(fileUrl);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
protocol.get(fileUrl, (response) => {
const fileStream = fs.createWriteStream(dest);
response.pipe(fileStream);
fileStream.on('finish', () => {
console.log('File downloaded successfully!');
});
}).on('error', (err) => {
console.error('Error downloading the file:', err.message);
});
}
downloadFile('https://example.com/path/to/file.jpg', filePath);