WebTorrent Client

2.8.5 · active · verified Tue Apr 21

WebTorrent is a versatile streaming BitTorrent client designed for both Node.js environments and web browsers. Currently stable at version 2.8.5, it receives frequent minor updates and bug fixes, with new features introduced periodically. Its primary differentiator is its ability to operate directly within a web browser using WebRTC data channels for peer-to-peer communication, making it the "streaming torrent client for the web." In Node.js, it functions as a standard torrent client utilizing TCP and UDP. This pure JavaScript library exposes torrent files as streams, supporting on-demand piece fetching, and can seamlessly switch between sequential and rarest-first piece selection strategies. WebTorrent facilitates connecting "web peers" (browser clients) with other WebTorrent-compatible clients, including desktop applications and specialized command-line tools like `webtorrent-hybrid`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a WebTorrent client, adds a magnet URI, logs download progress, and saves the torrent's files to a local directory once complete. It includes error handling and proper client cleanup.

import WebTorrent from 'webtorrent';
import fs from 'node:fs';

const client = new WebTorrent();

const magnetURI = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10'; // Example Sintel torrent (public domain)

client.add(magnetURI, { path: './downloads' }, (torrent) => {
  console.log(`Client is downloading torrent: ${torrent.infoHash}`);

  torrent.on('download', () => {
    console.log(`Downloaded: ${torrent.downloaded} bytes of ${torrent.length} total`);
  });

  torrent.on('done', () => {
    console.log('Torrent download finished!');
    torrent.files.forEach((file) => {
      console.log(`File name: ${file.name}, length: ${file.length}`);
      // Example: Stream a file to disk (Node.js only)
      const source = file.createReadStream();
      const destination = fs.createWriteStream(`./downloads/${file.name}`);
      source.pipe(destination);
      source.on('end', () => {
        console.log(`Finished writing ${file.name} to disk.`);
      });
    });
    client.destroy(); // Clean up client after download
  });

  torrent.on('error', (err) => {
    console.error('Torrent error:', err.message);
    client.destroy();
  });
});

client.on('error', (err) => {
  console.error('WebTorrent client error:', err.message);
});

view raw JSON →