Download a file on Node.js
To download a file on Node.js, you can use the built-in fs module and the https or http module to make a request to the server and save the response to a file.
Here's an example of how you can download a file using https module:
const https = require('https');
const fs = require('fs');
const fileUrl = 'https://example.com/file.pdf';
const filePath = './downloads/file.pdf';
const file = fs.createWriteStream(filePath);
https.get(fileUrl, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
console.log('File downloaded successfully.');
});
}).on('error', (err) => {
fs.unlink(filePath, () => {
console.error(`Error downloading file: ${err}`);
});
});
In the above example, we first define the URL of the file we want to download and the path where we want to save the file. We then create a write stream to the file using the fs module.
Next, we make a https.get() request to the server, passing the file URL as the first argument and a callback function as the second argument. In the callback function, we pipe the response to the write stream and listen for the 'finish' event to close the file and log a success message.
If an error occurs while downloading the file, we delete the incomplete file using fs.unlink() and log an error message.
Komentar
Posting Komentar