JavaScript / TypeScript
@fastblob/fastblob-fetch 是官方 JavaScript / TypeScript SDK:签名与原生 fetch 完全一致,传入接入域名的 URL,自动派生 0–9 子域并行拉取。TypeScript 编写、自带类型,MIT 许可。
npm install @fastblob/fastblob-fetchpnpm add @fastblob/fastblob-fetchimport fetch from '@fastblob/fastblob-fetch'
const response = await fetch('https://cdn.example.com/big-buck-bunny/video.mp4')const blob = await response.blob()const url = URL.createObjectURL(blob)input 支持 string、URL 与 Request,返回标准 Response——blob()、arrayBuffer()、json() 等都照常可用。
SDK 在 URL 主机名前依次加上 0. 到 9.,得到 10 个镜像地址:第 0 个作为首选,其余作为备用镜像,交给底层引擎 @fastblob/fast-fetch 按 HTTP Range 切块并行拉取、自动重试与拼合(详见工作原理)。
只有 GET 和 HEAD 请求会并行加速,其他方法原样透传给原生 fetch。
第二个参数在标准 RequestInit 之外多一个 fastFetch 字段:
const response = await fetch('https://cdn.example.com/models/llama-7b.gguf', { fastFetch: { maxRetries: 3, chunkCallback: (chunk, range, input) => { console.log(`收到 ${range[0]}–${range[1]}`) } }})| 选项 | 类型 | 说明 |
|---|---|---|
mirrorURLs | FetchInput[] | 追加额外镜像地址(在派生的 0–9 之后)。 |
maxRetries | number | 每个镜像的最大重试次数。 |
retryDelay | number | 重试间隔(毫秒)。 |
logger | Partial<Logger> | 自定义日志。 |
chunkCallback | (chunk, range, input) => void | 每收到一个分块时回调,可用于进度展示。 |
派生镜像地址
Section titled “派生镜像地址”需要自己控制镜像列表时(比如交给其他下载工具),用具名导出 getFastBlobInputs:
import { getFastBlobInputs } from '@fastblob/fastblob-fetch'
const mirrors = getFastBlobInputs('https://cdn.example.com/big-buck-bunny/video.mp4')// ['https://0.cdn.example.com/…', …, 'https://9.cdn.example.com/…']第二个参数可指定派生数量(默认 10)。镜像规则就一条:第 n 个镜像 = 在主机名前加 n.——其他语言可按此规则自行实现。
现代浏览器开箱即用;旧浏览器需要为以下能力提供 polyfill:
| 能力 | polyfill |
|---|---|
| AbortController | mo/abortcontroller-polyfill |
| Blob.stream | eligrey/Blob.js |
| Promise.any | zloirock/core-js |
| TransformStream | MattiasBuelens/web-streams-polyfill |