运行时依赖
安装命令
点击复制技能文档
WebTorrent — 流式 Torrent 客户端
一个运行在 Node.js 和浏览器中的 BitTorrent 客户端,使用纯 JavaScript 实现,零原生依赖。
使用场景
当用户需要下载 torrent/magnet 链接、种子和共享文件、实现浏览器端 P2P 传输、构建流式 torrent 媒体播放器或使用 webtorrent 相关功能时。
触发词
webtorrent、torrent 下载、magnet 链接、torrent、种子、P2P 传输、浏览器 torrent、WebRTC 文件共享、流式下载。
安装
npm install webtorrent
CLI 工具:npm install webtorrent-cli -g
快速开始
Node.js
import WebTorrent from 'webtorrent'
const client = new WebTorrent()
// 通过 magnet 链接下载
client.add(magnetURI, (torrent) => {
console.log('下载中:', torrent.infoHash)
torrent.files.forEach(file => {
console.log(文件:${file.name} (${file.length} bytes))
})
})
// 共享本地文件
client.seed('/path/to/file.mp4', (torrent) => {
console.log('共享中:', torrent.magnetURI)
})
浏览器 — ESM 导入
import WebTorrent from 'webtorrent'
const client = new WebTorrent()
client.add(magnetURI, (torrent) => {
torrent.files.forEach(file => {
file.getBuffer((err, buf) => {
if (err) throw err
console.log(下载完成:${file.name}, ${buf.length} bytes)
})
})
})
浏览器 — 脚本标签
核心 API
client.add(torrentId, [opts], [callback])
添加一个 torrent 开始下载。
torrentId — magnet URI / 信息散列 / torrent 文件 Buffer / 远程 .torrent URL
opts — 可选配置(见下文)
返回一个 Torrent 对象
client.add(magnetURI, { path: './downloads' }, (torrent) => {
console.log('元数据获取')
})
client.seed(input, [opts], [callback])
共享文件。
input — 文件路径 / 文件对象 / 文件列表 / Buffer / 可读流
在浏览器中,可以与拖放库一起使用
// 浏览器中的拖放文件共享
import dragDrop from 'drag-drop'
dragDrop('body', (files) => {
client.seed(files, (torrent) => {
console.log('共享中:', torrent.magnetURI)
})
})
client.destroy([callback])
销毁客户端并释放所有资源。
client.on('error', callback)
全局错误处理。
Torrent 对象
client.add(magnetURI, (torrent) => {
// 属性
torrent.infoHash // 字符串 — torrent 散列
torrent.magnetURI // 字符串 — magnet 链接
torrent.name // 字符串 — torrent 名称
torrent.files // 文件数组
torrent.progress // 数字 0-1
torrent.downloaded // 数字 — 下载字节
torrent.uploaded // 数字 — 上传字节
torrent.downloadSpeed // 字节/秒
torrent.uploadSpeed // 字节/秒
torrent.numPeers // 数字 — 连接的对等节点
torrent.path // 字符串 — 下载目录
torrent.ready // 布尔值 — 元数据准备就绪
// 事件
torrent.on('ready', () => {}) // 元数据准备就绪
torrent.on('download', (bytes) => {}) // 数据块接收
torrent.on('upload', (bytes) => {}) // 数据块发送
torrent.on('done', () => {}) // 下载完成
torrent.on('error', (err) => {}) // 错误
torrent.on('warning', (err) => {}) // 警告
torrent.on('wire', (wire) => {}) // 新对等节点连接
torrent.on('noPeers', () => {}) // 无可用对等节点
// 方法
torrent.pause() // 暂停
torrent.resume() // 恢复
torrent.destroy() // 删除
})
文件对象(torrent.files 的元素)
const file = torrent.files[0]
// 属性
file.name // 文件名
file.length // 文件大小(字节)
file.downloaded // 下载字节
file.progress // 下载进度 0-1
// 方法
file.getBuffer((err, buffer) => {}) // 获取完整 Buffer
file.getBlob((err, blob) => {}) // 获取 Blob(浏览器)
// 流式读取 — 创建可读流
const stream = file.createReadStream()
stream.pipe(someWritableStream)
// 渲染到页面
file.appendTo('#container') // 附加到 DOM 元素
file.renderTo('#container') // 替换 DOM 元素内容
// 流式视频播放
file.renderTo('video#player') // 渲染到