Skip to main content

API & Config

Create instance

var engine = new P2PEngineFile(url, p2pConfig);

Creates a new P2PEngineFile instance; url is the URL of the file to download.

If p2pConfig is provided, it overrides the default options shown below.

FieldTypeDefaultDescription
logLevelstring|boolean'error'Log level to print (warn, error, none; false=none, true=warn).
tokenstringundefinedToken used to aggregate and display multi-domain data on the console. Also required when customizing channelId.
trackerZonestring'eu'Country code for the tracker server address ('eu', 'hk', 'us').
p2pEnabledbooleantrueEnables or disables the P2P engine.
webRTCConfigObject{}A configuration dictionary for configuring WebRTC connections.
pieceLengthnumber1024 * 1024Length, in bytes, of each piece except the last one.
httpMaxRetrysnumber2Maximum number of retry attempts for HTTP file downloads.
mitmstring'https://cdnbye.github.io/file-p2p-engine/demo/mitm.html'The URL of your own man-in-the-middle page that installs the service worker in a secure context, hosted via an iframe on GitHub Pages.
diskCacheLimitObject{"pc": 1500 * 1024 * 1024, "mobile": 1000 * 1024 * 1024}Maximum size of binary data that can be stored in the disk cache.

P2PEngineFile API

P2PEngineFile.version (static)

Returns the current version of P2PEngineFile.

P2PEngineFile.protocolVersion (static)

Returns the P2P protocol version.

P2PEngineFile.isSupported() (static method)

Returns true if the browser supports WebRTC data channels.

engine.start()

Starts the file download.

engine.pause()

Pauses the file download.

engine.resume()

Resumes the file download.

engine.stop()

Stops downloading and P2P, and frees up resources.

engine.destroy()

Stops downloading and P2P, and frees up resources.

engine.isSaveByStreamSupported

Returns true if the browser supports saving files via a ServiceWorker stream.

engine.saveByServiceWorkerStream(filename)

Instructs the browser to save a file using response headers and a service worker.

P2PEngineFile Events

engine.on('metadata', function (source) {})

Returns the file's metadata, including:
source.getUrl(): the file's download URL
source.getMime(): the file's MIME type
source.getFileLength(): the file's size

engine.on('progress', function (ratio) {})

The current download progress.

engine.on('failed', function () {})

Emitted when the download fails; use this to fall back to a normal download, for example.

engine.on('speed', function (speed) {})

Average download speed (byte/s).

engine.on('finished', function (file) {})

Emitted when the download finishes; file is an object for handling the downloaded file, including:
file.save(fileName): saves the file as fileName
file.getBlobURL(): returns the blob URL
file.revokeBlobURL(): removes the reference to the blob URL and frees up resources

engine.on('peerId', function (peerId) {})

Emitted when this client's peer ID is received from the server.

engine.on('peers', function (peers) {})

Emitted when successfully connected to a new peer.

engine.on('stats', function (stats) {})

Emitted whenever data is downloaded or uploaded.
stats.totalHTTPDownloaded: total data downloaded via HTTP (KB).
stats.totalP2PDownloaded: total data downloaded via P2P (KB).
stats.totalP2PUploaded: total data uploaded via P2P (KB).
stats.p2pDownloadSpeed: P2P download speed (KB/s).

engine.on('serverConnected', function (connected) {})

Emitted when the WebSocket connection opens or closes.

engine.on('exception', function (e) {})

Emitted when an exception occurs.
e.code: Exception identifier(TRACKER_EXPT SIGNAL_EXPT)
e.message: Exception message.
e.stack: Exception stack trace.

Get P2P Information from p2pConfig

p2pConfig: {
getStats: function (totalP2PDownloaded, totalP2PUploaded, totalHTTPDownloaded, p2pDownloadSpeed) {
// get the downloading statistics
},
getPeerId: function (peerId) {
// get peer Id
},
getPeersInfo: function (peers) {
// get peers information
}
}

Advanced Usage

Dynamic File URL Path Support

Some URLs point to the same file but have different paths. For example, example.com/clientId1/fileId.file and example.com/clientId2/fileId.file. In this case, you can define a common channelId for them.

// Set token in p2pConfig before setting channelId!
p2pConfig: {
token: YOUR_TOKEN,
channelId: function (url) {
const fileId = extractFileIdFromUrl(url); // make a channelId by removing the different part which is defined by yourself
return fileId;
}
// channelId: VIDEO_ID // for fixed channel id
}