Open In App

What is WebTorrent and how to use it in Node.js ?

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

What is WebTorrent?

WebTorrent is a streaming torrent client for Node.js. WebTorrent is written in JavaScript-the language of the web. No extensions and plugins are required. Install it using npm only.
For to use WebTorrent in the browser, WebRTC (Web Real-Time Communication) is required.

Features of WebTorrent:

  • It is a torrent client for Node.js and browsers.
  • It is Very fast.
  • Can download multiple torrent files efficiently.
  • It is completely written in Pure Javascript.

Step 1: Create a Project folder:

mkdir Project

Step 2: Move to the created project folder and initialize npm init:

npm init

Step 3: Install using npm.

Now to install WebTorrent follow the commands given below:

npm install webtorrent

 

Run the above code in the terminal, e.g. Vscode terminal.

Also, you can install it globally by just adding ‘-g’ before the package name.

npm install -g webtorrent

 

or you can simply include the ‘webtorrent.min.js’ script given below to directly use WebTorrent.

<script src="https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js"></script>

Project structure: The project Structure should look like below:

 

Step 4: Check whether WebTorrent is installed or not and the version of WebTorrent.

Now you can check the version and the package installed in the package.json file under the dependencies.

Step 5: Install Browserify.

Browserify is a module that enables us to include node modules in our web projects. Browserify let us use require(‘modules’) in the browser by bundling all our dependencies. To install Browserify follow the command below.

npm install Browserify

 

Example 1: Now we can use WebTorrent. To test whether it working or not let’s make a small torrent video player, that only show the torrent file.

Approach:

  • Include the latest version of WebTorrent so that we can use WebTorrent Functionality.
  • Initialize WebTorrent.
  • Use the magnet link to download the torrent file.
  • Use the File Format as mp4.
  • Display the file by adding it to DOM using the file.appendTo().

Consider Javascript code as index.js and HTML code as index.html

Javascript




// Including modules
const WebTorrent = require('webtorrent');
// Initializing WebTorrent
const client = new WebTorrent()
 
// Using a magnet link
let NewMagnetTorrentId = 'Magnet Link'
// Starts downloading a new torrent file
client.add(NewMagnetTorrentId, function (torrent) {
    // Using the .mp4 file
    const file = torrent.files.find(function (Newfile) {
        // Returning filename ending with .mp4
        return Newfile.name.endsWith('.mp4')
    })
 
    // Display the file by adding it to the DOM.
    file.appendTo('body')
})


HTML




<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- title of the page -->
    <title>WebTorrent video player</title>
</head>
 
<body>
    <!-- Including script -->
    <script src="./app.js"></script>
</body>
</html>


Output: Run the command given below in the terminal.

In the command given below ‘index.js’ is the current file and ‘app.js’ is the name of the file which is getting created after conversion.

browserify index.js -o app.js

 

After that, a file named ‘app.js’ is created which is linked to the HTML file using the script tag.

Now you can open the HTML file(we are using an HTML file for just showing the output on the screen) using the live server or directly we can directly open the index.html file shown below.

 

Example 2: Make a Torrent file downloader using WebTorrent that downloads torrent files.

Approach:

  1. Use the latest version of WebTorrent so that we can use WebTorrent Functionality. 
  2. Initialize WebTorrent.
  3. Use the magnet link to download the torrent file.
  4. Preventing page refresh using preventDefault.
  5. Print the progress of downloading the file every 10 seconds.
  6. Render all the files into the same page. 
  7. Show the downloaded file.

Consider Javascript code as index.js and HTML code as index.html

Javascript




const WebTorrent = require('webtorrent');
 
// Initializing WebTorrent
const client = new WebTorrent()
 
// queryselector selects the 'form' and
//addEventListener listen the submit event
document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault() // As the submit event occur it prevent page refresh
 
    // selecting the form's input section
    const NewTorrentLink = document.querySelector(
                                    'form input[name=NewTorrentLink]').value
 
    // concatenate torrentId
    log('New Magnet Link: ' + NewTorrentLink)
 
    // starts downloading a new torrent
    client.add(NewTorrentLink, onTorrent)
})
 
// getting torrent metadata
function onTorrent(torrent) {
    log('<h3>Getting torrent metadata</h3>')
    log(
 
        // Info hash of the torrent string
        'Torrent Information: ' + torrent.infoHash
        // Magnet URI of torrent
    )
 
    // Showing the download progress every 10 second
    const NewInterval = setInterval(function () {
        log('Progress Reader: ' +
            (torrent.progress * 100).toFixed(1) + '%')
    }, 10000)
 
    // Emitted when all the files download 100%
    torrent.on('Completed The Process', function () {
        log('Progress: 100%')
        clearInterval(NewInterval)
    })
 
    // Render all files into to the page
    torrent.files.forEach(function (NewFile) {
 
        // Appending file with .Final
        NewFile.appendTo('.Final')
 
        // Getting a url that can be used to refer a file
        // and callback will be called once the file is ready
        NewFile.getBlobURL(function (errorfound, NewUrl) {
            if (errorfound) return log(errorfound.message)
            log('File Process done.')
            log('<a href="' + NewUrl + '">Download Complete File: '
                + NewFile.name + '</a>')
        })
    })
}
// Function log
function log(FinalString) {
 
    // Creating element 'p'
    const p = document.createElement('p')
    // setting HTML content
    p.innerHTML = FinalString
 
    // Selecting '.Final' and appending it to 'p'
    document.querySelector('.Final').appendChild(p)
}


HTML




<html>
<body>
    <h1>Download files using the WebTorrent</h1>
    <!-- creating a form the magnet link -->
    <form>
        <p>Download using magnet link: </p>
        <input name="NewTorrentLink" , value="">
        <!-- submit button to submit the magnet link -->
        <button type="submit">Download</button>
    </form>
 
    <h2>Logs for the downloading</h2>
    <!-- creating a class log -->
    <div class="Final"></div>
    <script src="./app.js"></script>
</body>
</html>


Output: Run the command given below in the terminal.

In the command given below ‘index.js’ is the current file and ‘app.js’ is the name of the file which is getting created after conversion.

browserify index.js -o app.js

 

After that, a file named ‘app.js’ is created which is linked to the HTML file using the script tag.

Now you can open the HTML file(we are using an HTML file for just showing the output on the screen) using the live server or directly we can directly open the index.html file shown below.  
 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads