nodejs-file-downloader is a simple utility for downloading files. It hides the complexity of dealing with streams, redirects, paths and duplicate file names. Can automatically repeat failed downloads.
If you encounter any bugs or have a question, please don't hesitate to open an issue.
Installation
$ npm install nodejs-file-downloader
Table of Contents
Examples
Basic
Download a large file with default configuration
const Downloader = require('nodejs-file-downloader');
(async () => {
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./downloads",
})
await downloader.download();
console.log('All done');
})();
Get the progress of a download
const Downloader = require('nodejs-file-downloader');
(async () => {
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./downloads/2020/May",
onProgress:function(percentage){
console.log('% ',percentage)
}
})
await downloader.download();
})();
Custom file name
Normally, nodejs-file-downloader "deduces" the file name, from the URL or the response headers. If you want to choose a custom file name, supply a config.fileName property.
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./downloads/2020/May",
fileName:'somename.zip'
})
Overwrite existing files
By default, nodejs-file-downloader uses config.cloneFiles = true, which means that files with an existing name, will have a number appended to them.
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./",
cloneFiles:false
})
Hook into response
If you need to get the underlying response, in order to decide whether the download should continue, or perform any other operations, use the onReponse hook.
function onResponse(response){
if(response.headers['content-length'] > 1000000){
console.log('File is too big!')
return false;
}
}
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./",
onResponse
})
await downloader.download()
Repeat failed downloads automatically
The program can repeat any failed downloads automatically. Only if the provided config.maxAttempts number is exceeded, an Error is thrown.
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./",
maxAttempts:3,
onError:function(error){
console.log('Error from attempt ',error)
}
})
try {
await downloader.dowload();
} catch (error) {
console.log('Final fail',error)
}