Socket
Socket
Sign inDemoInstall

webtorrent

Package Overview
Dependencies
Maintainers
1
Versions
529
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webtorrent

Streaming torrent client


Version published
Weekly downloads
3.4K
increased by2.37%
Maintainers
1
Weekly downloads
 
Created
Source

WebTorrent

Streaming torrent client for node & the browser

Build Status NPM Version NPM Downloads Gratipay

Sauce Test Status

WebTorrent is a streaming torrent client for node.js and the browser. YEP, THAT'S RIGHT. THE BROWSER. It's written completely in JavaScript – the language of the web – so the same code works in both runtimes.

In the browser, WebTorrent uses WebRTC (data channels) for peer-to-peer transport. It can be used without browser plugins, extensions, or installations. It's Just JavaScript™.

Simply include the webtorrent.min.js script on your page to start fetching files over WebRTC using the BitTorrent protocol, or require('webtorrent') with browserify. See demo apps and code examples below.

To make BitTorrent work over WebRTC (which is the only p2p transport that works on the web) we made some protocol changes. Therefore, a browser-based WebTorrent client can only connect to other clients that support WebTorrent (and WebRTC).

We hope established torrent clients (uTorrent, Transmission, Vuze, etc.) will add support for WebTorrent (and WebRTC) so they can swarm with both normal and web peers.

In node, this module acts like a normal torrent client, using TCP and UDP to talk to regular torrent clients. Soon, it will gain the ability to swarm with web peers, making it the first "hybrid" client.

Network

Warning: This is pre-alpha software. Watch/star to follow along with progress.

Features

  • Torrent client for node.js & the browser (same npm module!)
  • Insanely fast
  • Download multiple torrents simultaneously, efficiently
  • Pure Javascript (no native dependencies)
  • Exposes files as streams
    • Fetches pieces from the network on-demand so seeking is supported (even before torrent is finished)
    • Seamlessly switches between sequential and rarest-first piece selection strategy
  • Supports advanced torrent client features
  • Comprehensive test suite (runs completely offline, so it's reliable and fast)
Browser-only features
  • WebRTC data channels for lightweight peer-to-peer communication with no plugins
  • No silos. WebTorrent is a P2P network for the entire web. WebTorrent clients running on one domain can connect to clients on any other domain.
  • Stream video torrents into a <video> tag (webm (vp8, vp9) or mp4 (h.264))
Node-only features
  • Stream to AirPlay, Chromecast, VLC player, and many other devices/players

Ways to help

  • Join us in IRC on freenode at #webtorrent if you want to help with development, or you just want to hang out with some cool mad science hackers :)
  • Create a new issue to report bugs
  • Fix an issue. Note: WebTorrent is an OPEN Open Source Project!
  • Donate bitcoin if you believe in the vision and wish to support the project. Use Coinbase, or send to 1B6aystcqu8fd6ejzpmMFMPRqH9b86iiwh. (proof)

WebTorrent in production

  • Instant – Secure, anonymous, streaming file transfer [code]
  • Your app here! (send a PR or open an issue with your app's URL)

Install

With npm, run:

npm install webtorrent

Usage

WebTorrent is the first BitTorrent client that works in the browser, using open web standards (no plugins, just HTML5 and WebRTC)! It's easy to get started!

In the browser
Downloading a file is simple:
var WebTorrent = require('webtorrent')
var concat = require('concat-stream')

var client = new WebTorrent()

client.download(magnet_uri, function (torrent) {
  // Got torrent metadata!
  console.log('Torrent info hash:', torrent.infoHash)

  torrent.files.forEach(function (file) {
    // Get the file data as a Buffer (Uint8Array typed array)
    file.createReadStream().pipe(concat(function (buf) {

      // Append a link to download the file
      var a = document.createElement('a')
      a.download = file.name
      a.href = URL.createObjectURL(new Blob([ buf ]))
      a.textContent = 'download ' + file.name
      document.body.appendChild(a)
    }))
  })
})
Seeding a file is simple, too:
var dragDrop = require('drag-drop/buffer')
var WebTorrent = require('webtorrent')

var client = new WebTorrent()

// When user drops files on the browser, create a new torrent and start seeding it!
dragDrop('body', function (files) {
  client.seed(files, function onTorrent (torrent) {
    // Client is seeding the file!
    console.log('Torrent info hash:', torrent.infoHash)
  })
})
Streaming to an HTML5 video element? Also simple!
var WebTorrent = require('webtorrent')

var client = new WebTorrent()

client.download(magnet_uri, function (torrent) {
  // Got torrent metadata!
  console.log('Torrent info hash:', torrent.infoHash)

  // Let's say the first file is a webm (vp8) or mp4 (h264) video...
  var file = torrent.files[0]

  // Create a video element
  var video = document.createElement('video')
  video.controls = true
  document.body.appendChild(video)

  // Stream the video into the video tag
  file.createReadStream().pipe(video)
})
Browserify

WebTorrent works great with browserify, an npm module that let's you use node-style require() to organize your browser code and load modules installed by npm (as seen in the previous examples).

WebTorrent is also available as a standalone script (webtorrent.min.js) which exposes WebTorrent on the window object, so it can be used with just a script tag:

<script src="webtorrent.min.js"></script>
In node.js

WebTorrent also works in node.js, using the same npm module! It's mad science!

As a command line app

WebTorrent is available as a command line app. Here's how to use it:

$ npm install -g webtorrent
$ webtorrent --help

To download a torrent:

$ webtorrent magnet_uri

To stream a torrent to a device like AirPlay or Chromecast, just pass a flag:

$ webtorrent magnet_uri --airplay

There are many supported streaming options:

--airplay               Apple TV
--chromecast            Chromecast
--mplayer               MPlayer
--mpv                   MPV
--omx [jack]            omx [default: hdmi]
--vlc                   VLC
--xbmc                  XBMC
--stdout                standard out [implies --quiet]

In addition to magnet uris, webtorrent supports many ways to specify a torrent.

API

This API should work exactly the same in node and the browser. Open an issue if this is not the case.

client = new WebTorrent([opts])

Create a new WebTorrent instance.

If opts is specified, then the default options (shown below) will be overridden.

{
  dht: Boolean,          // Whether or not to enable DHT (default=true)
  maxPeers: Number,      // Max number of peers to connect to per torrent (default=100)
  nodeId: String|Buffer, // DHT protocol node ID (default=randomly generated)
  peerId: String|Buffer, // Wire protocol peer ID (default=randomly generated)
  storage: Function      // custom storage engine, or `false` to use in-memory engine
  tracker: Boolean,      // Whether or not to enable trackers (default=true)
  verify: Boolean        // Verify previously stored data before starting (default=false)
}
client.add(torrentId, [opts], [function ontorrent (torrent) {}])

Start downloading a new torrent. Aliased as client.download.

torrentId can be one of:

  • magnet uri (utf8 string)
  • torrent file (buffer)
  • info hash (hex string or buffer)
  • parsed torrent (from parse-torrent)
  • http/https url to a torrent file (string)
  • filesystem path to a torrent file (string)

If ontorrent is specified, then it will be called when this torrent is ready to be used (i.e. metadata is available). Note: this is distinct from the 'torrent' event which will fire for all torrents.

If you want access to the torrent object immediately in order to listen to events as the metadata is fetched from the network, then use the return value of client.add. If you just want the file data, then use ontorrent or the 'torrent' event.

client.seed(input, [opts], [function onseed (torrent) {}])

Start seeding a new torrent.

input can be any of the following:

  • path to the file or folder on filesystem (string)
  • W3C File object (from an <input> or drag and drop)
  • W3C FileList object (basically an array of File objects)
  • Node Buffer object (works in the browser)

Or, an array of File or Buffer objects.

If opts is specified, it should contain the following types of options:

  • options for create-torrent (to allow configuration of the .torrent file that is created)
  • options for client.add (see above)

If onseed is specified, it will be called when the client has begun seeding the file.

client.on('torrent', function (torrent) {})

Emitted when a torrent is ready to be used (i.e. metadata is available and storage is ready). See the torrent section for more info on what methods a torrent has.

client.remove(torrentId, [function callback (err) {}])

Remove a torrent from the client. Destroy all connections to peers and delete all saved file data. If callback is specified, it will be called when file data is removed.

client.destroy()

Destroy the client, including all torrents and connections to peers.

client.torrents[...]

An array of all torrents in the client.

client.get(torrentId)

Returns the torrent with the given torrentId. Convenience method. Easier than searching through the client.torrents array.

client.ratio

Seed ratio for all torrents in the client.

torrent api

torrent.infoHash

Get the info hash of the torrent.

torrent.magnetURI

Get the magnet URI of the torrent.

torrent.files[...]

An array of all files in the torrent. See the file section for more info on what methods the file has.

torrent.swarm

The attached bittorrent-swarm instance.

torrent.remove()

Alias for client.remove(torrent).

torrent.addPeer(addr)

Adds a peer to the underlying bittorrent-swarm instance.

torrent.select(start, end, [priority], [notify])

Selects a range of pieces to prioritize starting with start and ending with end (both inclusive) at the given priority. notify is an optional callback to be called when the selection is updated with new data.

torrent.deselect(start, end, priority)

Deprioritizes a range of previously selected pieces.

torrent.critical(start, end)

Marks a range of pieces as critical priority to be downloaded ASAP. From start to end (both inclusive).

torrent.createServer([opts])

Create an http server to serve the contents of this torrent, dynamically fetching the needed torrent pieces to satisfy http requests. Range requests are supported.

Returns an http.Server instance (got from calling http.createServer). If opts is specified, it is passed to the http.createServer function.

Visiting the root of the server / will show a list of links to individual files. Access individual files at /<index> where <index> is the index in the torrent.files array (e.g. /0, /1, etc.)

Here is a usage example:

var client = new WebTorrent()
client.add(magnet_uri, function (torrent) {
  // create HTTP server for this torrent
  var server = torrent.createServer()
  server.listen(port) // start the server listening to a port

  // visit http://localhost:<port>/ to see a list of files

  // access individual files at http://localhost:<port>/<index> where index is the index
  // in the torrent.files array

  // later, cleanup...
  server.close()
  client.destroy()
})

file api

file.name

File name, as specified by the torrent. Example: 'some-filename.txt'

file.path

File path, as specified by the torrent. Example: 'some-folder/some-filename.txt'

file.length

File length (in bytes), as specified by the torrent. Example: 12345

file.select()

Selects the file to be downloaded, but at a lower priority than files with streams. Useful if you know you need the file at a later stage.

file.deselect()

Deselects the file, which means it won't be downloaded unless someone creates a stream for it.

stream = file.createReadStream([opts])

Create a readable stream to the file. Pieces needed by the stream will be prioritized highly and fetched from the swarm first.

You can pass opts to stream only a slice of a file.

{
  start: startByte,
  end: endByte
}

Both start and end are inclusive.

file.getBlobURL(function callback (err, url) {})

Get a url which can be used in the browser to refer to the file.

The file will be fetched from the network with highest priority, and callback will be called when it is ready. callback must be specified and may be called with a an Error or the blob url (String) when the file data is available and ready to be used.

file.getBlobURL(function (err, url) {
  if (err) throw err
  var a = document.createElement('a')
  a.download = file.name
  a.href = url
  a.textContent = 'Download ' + file.name
  body.appendChild(a)
})

Modules

Most of the active development is happening inside of small npm modules which are used by WebTorrent.

The Node Way™

"When applications are done well, they are just the really application-specific, brackish residue that can't be so easily abstracted away. All the nice, reusable components sublimate away onto github and npm where everybody can collaborate to advance the commons." — substack from "how I write modules"

node.js is shiny

Modules

These are the modules I am writing to make WebTorrent work:

moduletestsversiondescription
webtorrenttorrent client (this module)
addr-to-ip-portcache for addr->ip:port
bittorrent-dhtdistributed hash table client
bittorrent-peerididentify client name/version
bittorrent-protocolbittorrent protocol stream
bittorrent-swarmbittorrent connection manager
bittorrent-trackerbittorrent tracker server/client
buffernode buffer api for the browser
create-torrentcreate .torrent files
ip-setefficient mutable ip set
load-ip-setload ip sets from local/network
magnet-uriparse magnet uris
parse-torrentparse torrent identifiers
parse-torrent-fileparse .torrent files
simple-peersimpler webrtc api
simple-websocketsimpler websocket api
string2compactconvert 'hostname:port' to compact
torrent-discoveryfind peers via dht and tracker
typedarray-to-bufferefficient buffer creation
ut_metadatametadata for magnet uris (ext)
ut_pexpeer discovery (ext)
webtorrent-swarmwebtorrent connection management
webtorrent-trackerwebtorrent tracker server/client
Todo
  • compress-sdp (compress sdp messages to lighten load on webtorrent trackers & dht)
  • protocol extension: protocol encryption
  • protocol extension: µTP
  • protocol extension: UPnP and NAT-PMP port forwarding
  • protocol extension: webseed support
  • webtorrent-dht

Contribute

WebTorrent is an OPEN Open Source Project. Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit.

WebTorrent is only possible due to the excellent work of the following contributors:

Feross AboukhadijehGitHub/ferossTwitter/@feross
Daniel PoschGitHub/dcposchTwitter/@dcposch
John HieseyGitHub/jhieseyTwitter/@jhiesey
Travis FischerGitHub/fisch0920Twitter/@fisch0920
AstroGitHub/astroTwitter/@astro1138
Iván TodorovichGitHub/ivantodorovichTwitter/@ivantodorovich
Mathias BuusGitHub/mafintoshTwitter/@mafintosh
Bob RenGitHub/bobrenjc93Twitter/@bobrenjc93
Clone the code
git clone https://github.com/feross/webtorrent.git
cd webtorrent
npm install
./bin/cmd.js --help
Enable debug logs

In node, enable debug logs by setting the DEBUG environment variable to the name of the module you want to debug (e.g. bittorrent-protocol, or * to print all logs).

DEBUG=* webtorrent

Of course, this also works for the development version:

DEBUG=* ./bin/cmd.js

In the browser, enable debug logs by running this in the developer console:

localStorage.debug = '*'

Disable by running this:

localStorage.removeItem('debug')
Clone all dependencies

WebTorrent is a modular BitTorrent client, so functionality is split up into many npm modules. You can git clone all the relevant dependencies with one command. This makes it easier to send PRs:

./bin/clone.sh

Talks about WebTorrent

Known issues

Downloads don't start on Chromebook

Chromebooks are set to refuse all incoming connections by default. To change this, run:

sudo iptables -P INPUT ACCEPT

License

MIT. Copyright (c) Feross Aboukhadijeh.

Magic

Keywords

FAQs

Package last updated on 30 Dec 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc