WebTorrent 详细部署教程

WebTorrent 是一个支持浏览器和 Node.js 的流式 Torrent 客户端,完全用 JavaScript 编写,利用 WebRTC 实现浏览器端的点对点传输,无需任何插件或安装。本文介绍 WebTorrent 在不同场景下的部署和使用方法。


📋 目录

  1. WebTorrent 简介
  2. 部署方式概览
  3. 方式一:浏览器端部署
  4. 方式二:Node.js 部署
  5. 方式三:命令行工具部署
  6. 方式四:桌面应用部署
  7. 方式五:Docker 自托管部署
  8. 核心 API 与事件
  9. 故障排除

🧠 WebTorrent 简介

WebTorrent 是一个流式 Torrent 客户端,核心特点如下:

特性 说明
跨环境 同一套代码可在 Node.js 和浏览器中运行
浏览器传输 基于 WebRTC 数据通道,无需插件
流式播放 支持视频、音频边下载边播放,支持拖拽跳转
纯 JavaScript 无原生依赖
跨域无限制 不同域名的 WebTorrent 客户端可互相连接

⚠️ 重要限制:浏览器版 WebTorrent 不支持 TCP/UDP 协议,只能连接支持 WebRTC 的客户端(如 WebTorrent Desktop、webtorrent-hybrid、Vuze 等)。


📦 部署方式概览

部署方式 适用场景 难度
浏览器端(CDN/ESM) 网站嵌入下载/播放功能 ⭐ 简单
浏览器端(NPM + 打包工具) 复杂前端项目集成 ⭐⭐ 中等
Node.js 后端服务、自动化脚本 ⭐⭐ 中等
命令行工具 终端下载/流式播放 ⭐ 简单
桌面应用 普通用户 GUI 客户端 ⭐ 简单
Docker 自托管 服务器部署 Web 版服务 ⭐⭐⭐ 稍复杂

🌐 方式一:浏览器端部署

浏览器端部署有 3 种方式,推荐根据项目类型选择。

1.1 使用 CDN(ES Module 方式)

最快捷的方式,适用于简单 HTML 页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebTorrent 播放器</title>
</head>
<body>
<h1>WebTorrent 下载与播放</h1>
<input id="magnetInput" placeholder="粘贴磁力链接" size="80" />
<button id="downloadBtn">下载</button>
<video id="player" controls width="800"></video>
<div id="fileList"></div>

<script type="module">
import WebTorrent from 'https://esm.sh/webtorrent/dist/webtorrent.min.js';

const client = new WebTorrent();
const player = document.getElementById('player');
const fileList = document.getElementById('fileList');

document.getElementById('downloadBtn').addEventListener('click', () => {
const magnetURI = document.getElementById('magnetInput').value.trim();
if (!magnetURI) return;

client.add(magnetURI, (torrent) => {
console.log('下载中:', torrent.infoHash);
fileList.innerHTML = '';

// 查找第一个视频文件并播放
const videoFile = torrent.files.find(f =>
f.name.match(/\.(mp4|webm|mkv|mov|avi)$/i)
);

if (videoFile) {
videoFile.streamTo(player);
}

// 显示所有文件名
torrent.files.forEach((file, i) => {
const div = document.createElement('div');
div.textContent = `${i+1}. ${file.name} (${(file.length / 1024 / 1024).toFixed(2)} MB)`;
fileList.appendChild(div);
});
});
});
</script>
</body>
</html>

1.2 使用 NPM + 打包工具(Browserify/Webpack)

适用于现代前端项目。

1
npm install webtorrent

Webpack 配置注意事项:WebTorrent 需要额外的 Webpack 配置,可以参考官方仓库中的 webpack 配置文件

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import WebTorrent from 'webtorrent';

const client = new WebTorrent();

// 下载磁力链接
const magnetURI = 'magnet:?xt=urn:btih:...';
client.add(magnetURI, (torrent) => {
torrent.files.forEach(file => {
// 流式输出到 video/audio 元素
file.streamTo(document.querySelector('video'));
});
});

// 拖拽上传并做种
import dragDrop from 'drag-drop';
dragDrop('body', (files) => {
client.seed(files, (torrent) => {
console.log('做种中:', torrent.magnetURI);
});
});

1.3 使用传统 Script 标签

1
2
3
4
5
<script type="module">
import WebTorrent from 'https://esm.sh/webtorrent/dist/webtorrent.min.js';
// 或使用 CDN 绝对路径
// import WebTorrent from 'https://cdn.jsdelivr.net/npm/webtorrent/dist/webtorrent.min.js';
</script>

🖥️ 方式二:Node.js 部署

在 Node.js 环境中,WebTorrent 使用 TCP/UDP 与普通 BitTorrent 客户端通信。

1
npm install webtorrent

下载并保存文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import WebTorrent from 'webtorrent';

const client = new WebTorrent();
const magnetURI = 'magnet:?xt=urn:btih:...';

client.add(magnetURI, { path: '/path/to/download' }, (torrent) => {
torrent.on('done', () => {
console.log('下载完成!');
client.destroy();
});

torrent.on('download', (bytes) => {
console.log(`已下载: ${(torrent.downloaded / 1024 / 1024).toFixed(2)} MB`);
console.log(`进度: ${(torrent.progress * 100).toFixed(1)}%`);
});
});

创建并做种文件

注意:要让 Node.js 做种的文件能被浏览器端 WebRTC 客户端下载,需要安装 webtorrent-hybrid

1
npm install webtorrent-hybrid
1
2
3
4
5
6
7
8
import WebTorrent from 'webtorrent-hybrid';

const client = new WebTorrent();

client.seed('/path/to/file.txt', (torrent) => {
console.log('做种中,磁力链接:', torrent.magnetURI);
console.log('InfoHash:', torrent.infoHash);
});

⌨️ 方式三:命令行工具部署

适合终端用户快速下载或流式播放。

1
npm install webtorrent-cli -g

基本用法

1
2
3
4
5
6
7
8
# 下载磁力链接
webtorrent "magnet:?xt=urn:btih:..."

# 下载并保存到指定目录
webtorrent "magnet:..." --path ./downloads

# 查看帮助
webtorrent --help

流式播放到设备

1
2
3
4
5
6
7
8
9
10
11
# 投屏到 Apple TV
webtorrent "magnet:..." --airplay

# 投屏到 Chromecast
webtorrent "magnet:..." --chromecast

# 使用 VLC 播放
webtorrent "magnet:..." --vlc

# 使用 MPV 播放
webtorrent "magnet:..." --mpv

🖥️ 方式四:桌面应用部署

WebTorrent Desktop 是官方提供的跨平台桌面应用,提供图形化界面,支持连接浏览器端的 WebRTC 客户端。

推荐安装方式

  1. 官网下载:访问 webtorrent.io/desktop 下载对应平台安装包

  2. macOS 使用 Homebrew

    1
    brew install --cask webtorrent

开发版构建(如需二次开发)

1
2
3
4
5
git clone https://github.com/webtorrent/webtorrent-desktop.git
cd webtorrent-desktop
npm install
npm run watch # 开发模式,代码变更自动重启
npm run package # 打包生产版本

打包平台说明

  • macOS 版本只能在 macOS 上打包
  • Windows 版本可在任意平台打包(需要 Wine + Mono)
  • Linux 版本可在任意平台打包

🐳 方式五:Docker 自托管部署

社区有 WebTorrent 的 Docker 自托管方案(Webtor),适合在服务器上部署 Web 版 Torrent 客户端。

快速启动

1
2
3
4
5
6
docker run -d \
-p 8080:8080 \
-v data:/data \
--name webtor \
--restart=always \
ghcr.io/webtor-io/self-hosted:latest

启动后访问 http://localhost:8080 即可使用 Web UI。

配置选项

1
2
3
4
5
6
7
8
# 配置域名
docker run -e DOMAIN=https://example.com -d ... ghcr.io/webtor-io/self-hosted:latest

# 配置自动清理(当磁盘空间不足时)
docker run \
-e CLEANER_FREE=35% \
-e CLEANER_KEEP_FREE=25% \
-d ... ghcr.io/webtor-io/self-hosted:latest
  • CLEANER_FREE:触发清理时释放的空间比例(默认 35%)
  • CLEANER_KEEP_FREE:触发清理的阈值(默认 25%)

容器管理

1
2
3
4
docker logs webtor          # 查看日志
docker stop webtor # 停止
docker start webtor # 启动
docker pull ghcr.io/webtor-io/self-hosted:latest # 更新镜像

🔌 核心 API 与事件

创建客户端

1
2
3
4
5
6
7
8
const client = new WebTorrent({
maxConns: 55, // 每个 Torrent 最大连接数
tracker: true, // 启用 Tracker
dht: true, // 启用 DHT(仅 Node.js)
utp: true, // 启用 uTP(仅 Node.js)
downloadLimit: -1, // 下载限速(字节/秒)
uploadLimit: -1 // 上传限速(字节/秒)
});

常用方法

方法 说明
client.add(torrentId, [opts], callback) 下载 Torrent,torrentId 支持磁力链接、种子文件、InfoHash、URL 等
client.seed(input, [opts], callback) 创建并做种新 Torrent
client.remove(torrentId, [opts], callback) 移除 Torrent
client.destroy(callback) 销毁客户端及所有连接
client.createServer([opts]) 创建 HTTP 服务器提供流式服务

Torrent 对象事件

事件 说明
torrent.on('ready') 元数据获取完成,Torrent 准备就绪
torrent.on('metadata') 元数据已获取(包含文件列表、分片哈希等)
torrent.on('done') 所有文件下载完成
torrent.on('download', bytes) 每次下载数据时触发,可用于监控进度
torrent.on('upload', bytes) 每次上传数据时触发
torrent.on('wire', wire) 连接新 Peer 时触发,可用于自定义协议扩展
torrent.on('error', err) Torrent 发生致命错误

File 对象方法

1
2
3
4
5
6
7
8
9
10
11
// 流式输出到 video/audio 元素(浏览器)
file.streamTo(document.querySelector('video'));

// 创建可读流(Node.js)
const stream = file.createReadStream({ start: 0, end: 1024 });

// 选择下载该文件(提高优先级)
file.select();

// 取消选择
file.deselect();

🔧 故障排除

1. 浏览器端无法找到 Peer

  • 确认对方客户端支持 WebRTC(如 WebTorrent Desktop、webtorrent-hybrid)
  • 浏览器版 WebTorrent 不支持 TCP/UDP 常规 BitTorrent Peer

2. Node.js 做种无法被浏览器下载

  • 需要安装 webtorrent-hybrid 替代普通 webtorrent

3. 开启调试日志

  • Node.js:设置环境变量 DEBUG=* webtorrent
  • 浏览器:在开发者控制台运行 localStorage.setItem('debug', '*')

4. Webpack 打包报错

  • 参考官方仓库中的 scripts/browser.webpack.js 配置文件进行额外配置

5. Docker 容器数据持久化

  • 确保使用 -v data:/data 挂载卷,所有下载数据存储在 /data 目录

📚 总结

你的需求 推荐方案
网站嵌入 Torrent 播放/下载功能 浏览器端(CDN 或 NPM)
后端自动化下载或处理 Torrent Node.js
终端快速下载/投屏 命令行工具
日常使用、无需技术背景 WebTorrent Desktop
服务器部署 Web 版 Torrent 服务 Docker 自托管

更多详细信息请参考: