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
文件。