advanced-downloader
v1.0.8
Published
高性能JavaScript下载管理器,支持断点续传和分片下载
Maintainers
Readme
advanced-downloader
一个高性能、功能全面的 JavaScript 下载管理器,专为现代前端应用设计。通过灵活的 API 和强大的核心功能,轻松实现复杂的文件下载需求,支持断点续下、分片并行下载和精确的进度监控。
特性
断点续传:支持暂停后从断点恢复下载,无需重新下载整个文件
分片下载:大文件自动分割为多个小块并行下载,显著提升速度
自动保存:下载完成后自动将文件保存到本地,无需手动处理
进度监控:实时跟踪下载进度、速度和剩余时间
灵活控制:提供完整的生命周期管理(启动、暂停、继续、取消)
错误处理:网络波动时自动重试,可配置重试次数和间隔
无框架依赖:可在 Vanilla JS、Vue、React、Angular 等任意环境使用
TypeScript 支持:提供完整的类型定义,提升开发体验
安装
# 使用npm
npm install advanced-downloader --save
# 使用yarn
yarn add advanced-downloader
# 使用pnpm
pnpm add advanced-downloader快速开始
基础用法
import { DownloadTask } from 'advanced-downloader';
// 创建下载任务
const task = new DownloadTask({
url: 'https://example.com/large-file.zip',
filename: 'my-file.zip',
// 进度更新回调
onProgress: (progress) => {
console.log(`进度: ${progress.percent.toFixed(2)}%`);
console.log(`速度: ${progress.speed} bytes/s`);
},
// 下载完成回调
onComplete: (file, info) => {
console.log(`下载完成: ${info.filename} (${info.totalSize} bytes)`);
},
// 错误处理回调
onError: (error) => {
console.error(`下载失败: ${error.message}`);
}
});
// 启动下载
try {
await task.start();
console.log('下载已启动');
} catch (error) {
console.error('启动下载失败:', error.message);
}Vue 3 示例
<template>
<div class="downloader">
<input v-model="url" placeholder="文件URL" />
<button @click="startDownload">开始下载</button>
<div v-if="progress.percent > 0" class="progress">
<div class="progress-bar" :style="{ width: `${progress.percent}%` }"></div>
<div class="progress-text">
{{ progress.percent.toFixed(1) }}% - {{ formatSize(progress.downloaded) }} / {{ formatSize(progress.total) }}
</div>
</div>
<div class="controls" v-if="isActive">
<button @click="pauseDownload">暂停</button>
<button @click="resumeDownload">继续</button>
<button @click="cancelDownload">取消</button>
</div>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { DownloadTask, formatBytes } from 'advanced-downloader';
const url = ref('https://example.com/file.zip');
const task = ref(null);
const progress = reactive({ percent: 0, downloaded: 0, total: 0 });
const startDownload = async () => {
task.value = new DownloadTask({
url: url.value,
onProgress: (p) => {
progress.percent = p.percent;
progress.downloaded = p.downloaded;
progress.total = p.total;
}
});
await task.value.start();
};
const pauseDownload = () => task.value?.pause();
const resumeDownload = () => task.value?.resume();
const cancelDownload = () => task.value?.cancel();
const formatSize = (bytes) => formatBytes(bytes);
</script>配置选项
创建DownloadTask时支持的配置参数:
new DownloadTask({
// 基础配置
url: 'https://example.com/file.zip', // 必选,下载URL
filename: 'custom-name.zip', // 可选,自定义文件名,默认从URL提取
method: 'GET', // 可选,HTTP方法,默认GET
headers: { // 可选,自定义请求头
'Authorization': 'Bearer token'
},
// 下载引擎配置
engine: 'auto', // 可选,引擎类型: 'auto' | 'xhr' | 'fetch'
withCredentials: false, // 可选,跨域请求是否携带Cookie
// 分片下载配置
chunked: true, // 可选,是否启用分片下载,默认true
chunkSize: 5 * 1024 * 1024, // 可选,分片大小(字节),默认5MB
concurrentChunks: 3, // 可选,并发下载的分片数量,默认3
// 错误处理配置
maxRetries: 3, // 可选,最大重试次数,默认3
retryDelay: 1000, // 可选,重试延迟(毫秒),默认1000
timeout: 30000, // 可选,超时时间(毫秒),默认30000
// 自动保存配置
autoSave: true, // 可选,是否自动保存文件,默认true
// 事件回调
onProgress: (progress) => {}, // 进度更新回调
onComplete: (file, info) => {}, // 下载完成回调
onError: (error) => {}, // 错误回调
onPause: () => {}, // 暂停回调
onCancel: () => {}, // 取消回调
onRetry: (attempt, maxAttempts) => {} // 重试回调
});方法与属性
任务方法
| 方法 | 说明 |
| --------------- | ---------------- |
| start() | 开始或恢复下载 |
| pause() | 暂停下载 |
| resume() | 恢复下载(同 start ()) |
| cancel() | 取消下载并清理资源 |
| getStatus() | 获取当前状态 |
| getProgress() | 获取当前进度信息 |
| getInfo() | 获取任务详细信息 |
进度对象(Progress)
| 属性 | 类型 | 说明 |
| --------------- | ------ | -------------- |
| percent | number | 下载进度百分比(0-100) |
| downloaded | number | 已下载字节数 |
| total | number | 总字节数 |
| speed | number | 下载速度(字节 / 秒) |
| remainingTime | number | 估计剩余时间(秒) |
任务信息(Info)
| 属性 | 类型 | 说明 |
| ---------------- | ------ | --------- |
| id | string | 任务唯一 ID |
| url | string | 下载 URL |
| filename | string | 文件名 |
| status | string | 当前状态 |
| totalSize | number | 文件总大小(字节) |
| downloadedSize | number | 已下载大小(字节) |
| startTime | Date | 开始时间 |
| endTime | Date | 结束时间 |
| duration | number | 总耗时(毫秒) |
工具函数
formatBytes
格式化字节数为人类可读的单位:
import { formatBytes } from 'advanced-downloader';
console.log(formatBytes(1024)); // "1.00 KB"
console.log(formatBytes(1048576)); // "1.00 MB"
console.log(formatBytes(20971520, 1)); // "20.0 MB"兼容性
浏览器:Chrome 60+、Firefox 55+、Edge 16+、Safari 10.1+
Node.js:不支持(仅适用于浏览器环境)
许可证
MIT
