{"skill":{"slug":"webtorrent","displayName":"WebTorrent — Streaming Torrent Client","summary":"Use WebTorrent to implement streaming BitTorrent client functionality in Node.js and the browser. Supports torrent downloading, seeding, magnet links, stream...","description":"---\nname: webtorrent\ndescription: Use WebTorrent to implement streaming BitTorrent client functionality in Node.js and the browser. Supports torrent downloading, seeding, magnet links, streaming media playback, and peer-to-peer transfer (via WebRTC Data Channel in the browser, and TCP/UDP in Node.js).\n---\n\n# WebTorrent — Streaming Torrent Client\n\nA BitTorrent client that runs in both Node.js and the browser, implemented in pure JavaScript with zero native dependencies.\n\n## Use Cases\n\nUse when users need to download torrent/magnet links, seed and share files, implement browser-side P2P transfer, build streaming torrent media players, or use webtorrent-related features.\n\n## Trigger Words\n\nwebtorrent, torrent download, magnet link, torrent, seeding, P2P transfer, browser torrent, WebRTC file sharing, streaming download.\n\n## Installation\n\n```bash\nnpm install webtorrent\n```\n\nCLI tool:\n```bash\nnpm install webtorrent-cli -g\n```\n\n## Quick Start\n\n### Node.js\n\n```js\nimport WebTorrent from 'webtorrent'\n\nconst client = new WebTorrent()\n\n// Download via magnet link\nclient.add(magnetURI, (torrent) => {\n  console.log('Downloading:', torrent.infoHash)\n\n  torrent.files.forEach(file => {\n    console.log(`File: ${file.name} (${file.length} bytes)`)\n  })\n})\n\n// Seed — share local files\nclient.seed('/path/to/file.mp4', (torrent) => {\n  console.log('Seeding:', torrent.magnetURI)\n})\n```\n\n### Browser — ESM import\n\n```js\nimport WebTorrent from 'webtorrent'\n\nconst client = new WebTorrent()\n\nclient.add(magnetURI, (torrent) => {\n  torrent.files.forEach(file => {\n    file.getBuffer((err, buf) => {\n      if (err) throw err\n      console.log(`Download complete: ${file.name}, ${buf.length} bytes`)\n    })\n  })\n})\n```\n\n### Browser — script tag\n\n```html\n<script type=\"module\">\n  import WebTorrent from 'https://esm.sh/webtorrent'\n  // Or local: import WebTorrent from 'webtorrent.min.js'\n\n  const client = new WebTorrent()\n  // ... same as above\n</script>\n```\n\n## Core API\n\n### `client.add(torrentId, [opts], [callback])`\n\nAdd a torrent to start downloading.\n\n- `torrentId` — magnet URI / info hash / torrent file Buffer / remote `.torrent` URL\n- `opts` — Optional configuration (see below)\n- Returns a `Torrent` object\n\n```js\nclient.add(magnetURI, { path: './downloads' }, (torrent) => {\n  console.log('Metadata obtained')\n})\n```\n\n### `client.seed(input, [opts], [callback])`\n\nSeed and share files.\n\n- `input` — File path / File object / FileList / Buffer / ReadableStream\n- In the browser, can be used with drag-drop libraries\n\n```js\n// Drag-and-drop file seeding in the browser\nimport dragDrop from 'drag-drop'\n\ndragDrop('body', (files) => {\n  client.seed(files, (torrent) => {\n    console.log('Seeding:', torrent.magnetURI)\n  })\n})\n```\n\n### `client.destroy([callback])`\n\nDestroy the client and release all resources.\n\n### `client.on('error', callback)`\n\nGlobal error handling.\n\n## Torrent Object\n\n```js\nclient.add(magnetURI, (torrent) => {\n  // Properties\n  torrent.infoHash    // string — torrent hash\n  torrent.magnetURI   // string — magnet link\n  torrent.name        // string — torrent name\n  torrent.files       // File[] — file list\n  torrent.progress    // number 0-1\n  torrent.downloaded  // number — bytes downloaded\n  torrent.uploaded    // number — bytes uploaded\n  torrent.downloadSpeed // bytes/s\n  torrent.uploadSpeed   // bytes/s\n  torrent.numPeers    // number — connected peers\n  torrent.path        // string — download directory\n  torrent.ready       // boolean — metadata ready\n\n  // Events\n  torrent.on('ready', () => {})      // Metadata ready\n  torrent.on('download', (bytes) => {})  // Data chunk received\n  torrent.on('upload', (bytes) => {})    // Data chunk sent\n  torrent.on('done', () => {})       // Download complete\n  torrent.on('error', (err) => {})   // Error\n  torrent.on('warning', (err) => {}) // Warning\n  torrent.on('wire', (wire) => {})   // New peer connected\n  torrent.on('noPeers', () => {})    // No peers available\n\n  // Methods\n  torrent.pause()    // Pause\n  torrent.resume()   // Resume\n  torrent.destroy()  // Remove torrent\n})\n```\n\n## File Object (element of torrent.files)\n\n```js\nconst file = torrent.files[0]\n\n// Properties\nfile.name       // Filename\nfile.length     // File size (bytes)\nfile.downloaded // Bytes downloaded\nfile.progress   // Download progress 0-1\n\n// Methods\nfile.getBuffer((err, buffer) => {})  // Get complete Buffer\nfile.getBlob((err, blob) => {})      // Get Blob (browser)\n\n// Streaming read — create a readable stream\nconst stream = file.createReadStream()\nstream.pipe(someWritableStream)\n\n// Render to page\nfile.appendTo('#container')          // Append to DOM element\nfile.renderTo('#container')          // Replace DOM element content\n\n// Streaming video playback\nfile.renderTo('video#player')        // Render to <video> tag\nfile.renderTo('img#preview')         // Render to <img> tag\nfile.renderTo('audio#player')        // Render to <audio> tag\n```\n\n## Browser WebRTC Considerations\n\n- **Browsers only support WebRTC** (no TCP/UDP direct connection)\n- **Can only connect to peers that support WebTorrent** (WebTorrent Desktop, webtorrent-hybrid, Instant.io, Vuze)\n- **Domains within the same SWARM can communicate** — WebTorrent is a web-wide P2P network\n- Supported browsers: Chrome, Firefox, Opera, Safari\n- Supported video formats: webm, mkv, mp4, ogv, mov (AV1, H264, HEVC, VP8, VP9)\n\n## Connecting Node.js to Browser Peers\n\nNative Node.js webtorrent only uses TCP/UDP and **cannot directly connect to browser WebRTC peers**. For bidirectional communication, use:\n\n```bash\nnpm install webtorrent-hybrid\n```\n\n```js\nimport WebTorrent from 'webtorrent-hybrid'\n// API is identical, but additionally supports WebRTC\n```\n\n## Common Options\n\n```js\nconst client = new WebTorrent({\n  maxConns: 55,           // Maximum number of connections\n  dht: true,              // Enable DHT\n  tracker: true,          // Enable tracker\n  webSeeds: true,         // Enable web seeds\n  lsd: true,              // Enable local service discovery\n  utp: true,              // Enable μTP (Node only)\n  downloadLimit: -1,      // Download rate limit (bytes/s), -1 = unlimited\n  uploadLimit: -1         // Upload rate limit (bytes/s), -1 = unlimited\n})\n\nclient.add(magnetURI, {\n  path: './downloads',      // Download directory\n  store: 'auto',            // Storage strategy: 'auto' | MemoryStorage | custom\n  destroyStoreOnDestroy: false,  // Delete files on destroy\n  private: false,           // Use private trackers only\n  announce: ['wss://...'],  // Custom tracker list\n  deselect: false,          // true = do not auto-select files to download\n  strategy: 'sequential'    // 'sequential' | 'rarest'\n})\n```\n\n## CLI Usage\n\n```bash\n# Download a magnet link\nwebtorrent magnet_uri\n\n# Stream to various devices\nwebtorrent magnet_uri --airplay    # Apple TV\nwebtorrent magnet_uri --chromecast # Chromecast\nwebtorrent magnet_uri --vlc        # VLC\nwebtorrent magnet_uri --mpv        # MPV\nwebtorrent magnet_uri --mplayer    # MPlayer\nwebtorrent magnet_uri --xbmc       # XBMC\nwebtorrent magnet_uri --stdout     # Standard output\n```\n\n## Common Patterns\n\n### Pattern 1: Download and Play Video (Browser)\n\n```js\nclient.add(magnetURI, (torrent) => {\n  const file = torrent.files.find(f => f.name.endsWith('.mp4'))\n  if (file) file.renderTo('video#player')\n})\n```\n\n### Pattern 2: Download Progress Display\n\n```js\nclient.add(magnetURI, (torrent) => {\n  torrent.on('download', () => {\n    const pct = (torrent.progress * 100).toFixed(1)\n    console.log(`Progress: ${pct}% | Speed: ${formatSpeed(torrent.downloadSpeed)}`)\n  })\n\n  torrent.on('done', () => {\n    console.log('Download complete!')\n  })\n})\n\nfunction formatSpeed(bps) {\n  const units = ['B/s', 'KB/s', 'MB/s']\n  let i = 0\n  while (bps >= 1024 && i < units.length - 1) { bps /= 1024; i++ }\n  return `${bps.toFixed(1)} ${units[i]}`\n}\n```\n\n### Pattern 3: Select Specific Files to Download\n\n```js\nclient.add(magnetURI, { deselect: true }, (torrent) => {\n  // After metadata is ready, only select needed files\n  torrent.on('ready', () => {\n    torrent.files.forEach(file => {\n      if (file.name.endsWith('.mp4')) file.select()\n      else file.deselect()\n    })\n  })\n})\n```\n\n### Pattern 4: In-Memory Temporary Storage\n\n```js\nimport MemoryChunkStore from 'memory-chunk-store'\n\nclient.add(magnetURI, { store: MemoryChunkStore }, (torrent) => {\n  // Data stored in memory, not written to disk\n  torrent.on('done', () => {\n    torrent.files[0].getBuffer((err, buf) => {\n      console.log(`Completed in memory: ${buf.length} bytes`)\n    })\n  })\n})\n```\n\n## Peer Discovery Mechanisms\n\n| Mechanism | Description | Node | Browser |\n|-----------|-------------|------|---------|\n| DHT | Distributed Hash Table | ✅ | ✅ (WebRTC) |\n| Tracker | Centralized tracking server | ✅ | ✅ (WebSocket) |\n| LSD | Local Service Discovery | ✅ | ❌ |\n| ut_pex | Peer Exchange Extension | ✅ | ✅ |\n\n## FAQ\n\n- **Cannot connect to regular torrents in the browser** — Browsers only connect via WebRTC; peers must also support WebTorrent\n- **Slow download speed** — Check the number of peers, whether DHT/tracker is enabled, and whether there are enough seeders\n- **Metadata loading slowly** — magnet URIs need to obtain metadata via ut_metadata first, which takes time\n- **Large file memory overflow** — Pay attention to memory limits in the browser; large files are recommended to use IndexedDB storage or streaming processing\n\nFor the detailed API reference, see [references/api-reference.md](references/api-reference.md).","topics":["Browser"],"tags":{"latest":"1.0.0"},"stats":{"comments":0,"downloads":339,"installsAllTime":13,"installsCurrent":0,"stars":0,"versions":1},"createdAt":1778116253936,"updatedAt":1778492864292},"latestVersion":{"version":"1.0.0","createdAt":1778116253936,"changelog":"Initial release of the webtorrent skill providing streaming BitTorrent client features for Node.js and browsers.\n\n- Supports torrent downloading, seeding, magnet links, and media streaming.\n- Works in both Node.js (TCP/UDP) and browser (WebRTC Data Channel) environments.\n- Exposes a simple API for adding, seeding, and managing torrents and files.\n- Includes core usage examples for Node.js and browsers, plus CLI tool instructions.\n- Offers options for torrent selection, storage strategy, bandwidth limits, and media playback integration.","license":"MIT-0"},"metadata":null,"owner":{"handle":"openlark","userId":"s1727wv2g20pc729snzcm4nf8183hy72","displayName":"OpenLark","image":"https://avatars.githubusercontent.com/u/260858787?v=4"},"moderation":null}