fetch in chunks
v1.3.0
用于分块获取大文件的实用程序,支持并行下载、进度跟踪和请求中止。
使用 npm 安装包:
npm 安装 fetch-in-chunks
从 'fetch-in-chunks' 导入 fetchInChunks;
异步函数 fetchInChunks(url, options = {})
url
( string
): 要下载的文件的 URL。
options
( object
, 可选): 包含附加选项的对象。
options.chunkSize
( number
, default: 5 * 1024 * 1024
): 要下载的每个块的大小(以字节为单位)。
options.maxParallelRequests
( number
, default: 1
): 并行下载的块数。
options.progressCallback
( function
, 可选):将使用下载的字节数和文件的总大小调用的回调函数。
options.signal
( AbortSignal
,可选):可用于中止下载的AbortSignal
对象。
Promise<Blob>
:解析为包含下载文件的Blob
的 Promise。
从 'fetch-in-chunks' 导入 fetchInChunks; 异步函数 downloadFile() { 尝试{const blob =等待fetchInChunks('https://example.com/largefile.zip');return blob; } catch (error) {console.error('获取文件时出错:', error); }}下载文件();
从 'fetch-in-chunks' 导入 fetchInChunks; 异步函数 downloadFileWithProgress() { 尝试{const blob =等待fetchInChunks('https://example.com/largefile.zip',{progressCallback:(下载,总计)=> {console.log(`已下载$ {((下载/总计)* 100) .toFixed(2)}%`);返回blob; } catch (error) {console.error('获取文件时出错:', error); }}downloadFileWithProgress();
AbortController
import fetchInChunks from 'fetch-in-chunks';异步函数 downloadFileWithAbort() { const 控制器 = new AbortController(); const 信号=控制器.信号; 尝试 {const blob = wait fetchInChunks('https://example.com/largefile.zip', { signal,});return blob; } catch (error) {if (error.name === 'AbortError') { console.log('下载中止');} else { console.error('获取文件时出错:', error);} } // 随时中止下载 控制器.abort();}
该项目根据 Apache 2.0 许可证获得许可。有关详细信息,请参阅LICENSE
文件。