@particle/fetch-file
Download a file, report progress, retry when appropriate, and verify integrity of downloaded bits.
Installation
npm install @particle/fetch-file --save
const fetchFile = require('@particle/fetch-file');
API
@particle/fetch-file
module.exports(url, destination, [options], state) ⇒ Promise.<(DowloadedFile|Error)>
⏏
Tries really, really, really hard to download a file, verifying integrity of
the downloaded bits and optionally reporting progress along the way. Also
supports cancellation.
Kind: Exported function
Returns: Promise.<(DowloadedFile|Error)>
- A promise for the downloaded file or
an error
url | string | | The URL for the file you'd like to download |
destination | string | | Path where downloaded bits will be saved |
[options] | object | | |
[options.signal] | object | | AbortSignal object as defined in https://dom.spec.whatwg.org/#interface-AbortSignal (optional) |
[options.headers] | object | | Request headers as key-value map object (optional) |
[options.maxRetries] | number | 3 | How many times to retry before giving up (optional) |
[options.onProgress] | onProgress | | Function to call with progess info (optional) |
[options.interval] | number | 100 | How often to report progress in milliseconds (optional) |
[options.algorithm] | string | "sha256" | Algorith to use when verifying checksum - supports whatever node's crypto.createHash() method does (optional) |
state | InternalState | | |
Example
const result = await fetchFile(url, tmpFile.path);
const onProgress = (progress) => console.log(progress);
const result = await fetchFile(url, tmpFile.path, { onProgress, interval: 250 });
const result = await fetchFile(url, tmpFile.path, { maxRetries: 0 });
const { AbortController } = fetchFile;
const controller = new AbortController();
try {
setTimeout(() => controller.abort(), 50);
await fetchFile(url, tmpFile.path, { signal });
} catch (error){
error.type;
error.name;
error.message;
}
module.exports~DowloadedFile : Object
Info about the downloaded file
Kind: inner typedef of module.exports
Properties
filename | string | Filename of downloaded file |
hash | string | Checksum for downloaded file |
module.exports~Progress : Object
Progress data passed to onProgress
callback
Kind: inner typedef of module.exports
Properties
length | number | size in bytes of your file |
transferred | number | bytes processed |
remaining | number | bytes remaining to be processed |
percentage | number | percentage of bytes transferred (0-100) |
module.exports~onProgress : function
Kind: inner typedef of module.exports
progress | Progress | progress info for file |
NOTE: Unfortunately, docs have a nasty habit of falling out of date. When in doubt, check usage in tests