Skip to main content

API & Config

Create instance

var engine = new P2PEngineFile(url, p2pConfig);

Create a new P2PEngineFile instance, url is the downloading file url.

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

FieldTypeDefaultDescription
logLevelstring|boolean'error'Print log level(warn, error, none,false=none, true=warn).
tokenstringundefinedToken is used to summarize and display multi domain name data on the console. In addition, token is required while customizing channelId.
trackerZonestring'eu'The country code name of the tracker server address('eu', 'hk', 'us').
p2pEnabledbooleantrueEnable or disable p2p engine.
webRTCConfigObject{}A Configuration dictionary providing options to configure WebRTC connections.
pieceLengthnumber1024 * 1024Length in bytes of every piece but the last one.
httpMaxRetrysnumber2Maximum retry times of file download by HTTP.
showSloganbooleanfalseDisplay slogan of cdnbye on console.
mitmstring'https://cdnbye.github.io/file-p2p-engine/demo/mitm.html'The address of own man in the middle that installs the service worker in a secure context hosted on github static pages from an iframe.
diskCacheLimitObject{"pc": 1500 1024 1024, "mobile": 1000 1024 1024}The max size of binary data that can be stored in the disk cache.

P2PEngineFile API

P2PEngineFile.version (static)

Get the version of P2PEngineFile.

P2PEngineFile.protocolVersion (static)

Get the version of P2P protocol.

P2PEngineFile.isSupported() (static method)

Returns true if WebRTC data channel is supported by the browser.

engine.start()

Start file download.

engine.pause()

Pause file download.

engine.resume()

Resume file download.

engine.stop()

Stop downloading and p2p, free used resources.

engine.destroy()

Stop downloading and p2p, free used resources.

engine.isSaveByStreamSupported

Returns true if save file by ServiceWorker stream is supported by the browser.

engine.saveByServiceWorkerStream(filename)

Instruct the browser to save a file using some response header + service worker.

P2PEngineFile Events

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

Get the metadata of file,including:
source.getUrl():The download address of file
source.getMime():The mime type of file
source.getFileLength():The size of file

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

Download progress.

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

Emitted when download failed, do something like fallback to normal download.

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

Mean download speed(byte/s).

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

Emitted when download finished, file is an object to handle the downloaded file, including:
file.save(fileName):Save file with fileName
file.getBlobURL():Get the blob URL
file.revokeBlobURL():Remove reference to BlobURL and free used resources

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

Emitted when the peer Id of this client is obtained from server.

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

Emitted when successfully connected with new peer.

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

Emitted when data is downloaded/uploaded.
stats.totalHTTPDownloaded: total data downloaded by HTTP(KB).
stats.totalP2PDownloaded: total data downloaded by P2P(KB).
stats.totalP2PUploaded: total data uploaded by P2P(KB).
stats.p2pDownloadSpeed: p2p download speed(KB/s).

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

Emitted when websocket is opened/closed.

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

Emitted when exception occured.
e.code: Exception identifier(TRACKER_EXPT SIGNAL_EXPT)
e.message: Exception message
e.stack: Exception stack

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 on them. For example, example.com/clientId1/fileId.file and example.com/clientId2/fileId.file. In this case, you can format 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
}