nodejs-file-downloader is a simple utility for downloading files. It hides the complexity of dealing with streams, paths and duplicate file names. Can automatically repeat failed requests.
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
})
Get response and then download
There is an alternative way to using Downloader.download():
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./",
})
const response = await downloader.request()
if(response.headers['content-length'] < 1000000){
await downloader.save()
}else{
console.log('File is too big!')
}
Repeat failed requests automatically
The program can repeat any failed http request automatically. Only if the provided config.maxAttempts number is exceeded, an Error is thrown.
Note that currently only the http requests will be repeated in case of an error, BUT NOT THE STREAM ITSELF. If a stream fails on its first attempt, an error is thrown as usual. I will change this behavior in the future.
const downloader = new Downloader({
url: 'http://212.183.159.230/200MB.zip',
directory: "./",
maxAttempts:3,
onError:function(error){
console.log('Error from attempt ',error)
}
})
await downloader.dowload();