What is WebTorrent and how to use it in Node.js ?
Last Updated :
28 Mar, 2023
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
const WebTorrent = require( 'webtorrent' );
const client = new WebTorrent()
let NewMagnetTorrentId = 'Magnet Link'
client.add(NewMagnetTorrentId, function (torrent) {
const file = torrent.files.find( function (Newfile) {
return Newfile.name.endsWith( '.mp4' )
})
file.appendTo( 'body' )
})
|
HTML
<!DOCTYPE html>
< html >
< head >
< meta charset = "UTF-8" >
< title >WebTorrent video player</ title >
</ head >
< body >
< 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:
- Use the latest version of WebTorrent so that we can use WebTorrent Functionality.
- Initialize WebTorrent.
- Use the magnet link to download the torrent file.
- Preventing page refresh using preventDefault.
- Print the progress of downloading the file every 10 seconds.
- Render all the files into the same page.
- Show the downloaded file.
Consider Javascript code as index.js and HTML code as index.html.
Javascript
const WebTorrent = require( 'webtorrent' );
const client = new WebTorrent()
document.querySelector( 'form' ).addEventListener( 'submit' , function (e) {
e.preventDefault()
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 >
< form >
< p >Download using magnet link: </ p >
< input name = "NewTorrentLink" , value = "" >
< button type = "submit" >Download</ button >
</ form >
< h2 >Logs for the downloading</ h2 >
< 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.
Share your thoughts in the comments
Please Login to comment...