To download files from a URL in Node.js, you can use the node-downloader-helper
library. It is a node module that helps in downloading large files over HTTP(S) protocol. It provides various options such as progress reporting, pausing and resuming the downloads, and more.
Here are the steps to use the node-downloader-helper
library to download files from a URL in Node.js:
- Install the
node-downloader-helper
library:
npm install node-downloader-helper --save
- Require the
DownloaderHelper
class from thenode-downloader-helper
module:
1 |
const DownloaderHelper = require('node-downloader-helper'); |
- Create a new instance of the
DownloaderHelper
class with the URL of the file to download:
1 |
const download = new DownloaderHelper('http://example.com/file.zip', __dirname); |
Here, the first argument is the URL of the file to download, and the second argument is the directory where the downloaded file will be saved.
- Register event listeners to get the progress and status of the download:
1 2 3 4 5 6 7 8 9 10 11 |
download.on('progress', stats => { console.log('Downloaded', stats.downloaded, 'bytes'); }); download.on('end', () => { console.log('Download complete'); }); download.on('error', err => { console.error('Download failed', err); }); |
Here, the progress
event is emitted every time a chunk of data is downloaded, and the end
event is emitted when the download is complete. The error
event is emitted if there is an error during the download.
- Start the download using the
start
method:
1 |
download.start(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const DownloaderHelper = require('node-downloader-helper'); const download = new DownloaderHelper('http://example.com/file.zip', __dirname); download.on('progress', stats => { console.log('Downloaded', stats.downloaded, 'bytes'); }); download.on('end', () => { console.log('Download complete'); }); download.on('error', err => { console.error('Download failed', err); }); download.start(); |