Skip to main content

Usage

Getting Started

Copy the demo html to your IDE and open 2 pages to check p2p.

Register Domain

Register your domain to activate P2P service.

tip

Localhost is always whitelisted. This means that you do not have to configure anything to perform tests locally.

Prepare

CORS

Make sure your file servers have proper CORS (Cross-origin resource sharing) headers so that data can be fetched across domain.

OPTIONS REQUEST

OPTIONS requests are mandatory to be able to perform RANGE requests in a cross-domain environment. The general idea is to add the following header to the HTTP response:

Access-Control-Allow-Methods: GET, OPTIONS

RANGE REQUEST

RANGE requests is required by P2P. Add the following header to the HTTP response:

Access-Control-Allow-Headers: Range

Some browsers such as Firefox, need to set Access-Control-Expose-Headers in the HTTP response header to get the file size:

Access-Control-Expose-Headers: Content-Length

Include

Script

Include the pre-built script of latest version:

<script src="https://cdn.jsdelivr.net/npm/@swarmcloud/file"></script>

File

Click me
This needs to be included before your player code. You can either prepend it to your compiled code or include it in a <script> before it.

Browserify / Webpack

npm install --save @swarmcloud/file

To include @swarmcloud/file you need to require it in the player module:

var P2PEngineFile = require('@swarmcloud/file');

If you are using ES6's import syntax:

import P2PEngineFile from '@swarmcloud/file';

Usage

Create P2PEngineFile instance passing url as parameter.

var downloader = new P2PEngineFile('path/to/your.file');
downloader.on('finished', function (file) {
file.save('name.file');
file.revokeBlobURL(); // free the blob
});
downloader.on('failed', function (e) {
// fallback to normal download
});
downloader.on('progress', function (e) {
// show progress to user
});
downloader.start();

Save file by ServiceWorker Stream

Instead of saving data in client-side storage or in memory then save by blob url, you could now actually create a writable stream directly to the file system. This is accomplished by emulating how a server would instruct the browser to save a file using some response header + service worker. It will create an own man in the middle that installs the service worker in a secure context hosted on github static pages from an iframe. You can host the mitm.html by yourself.

var downloader = new P2PEngineFile('path/to/your.file'{
// mitm: './mitm.html', // https://github.com/cdnbye/file-p2p-engine/blob/master/demo/mitm.html
});
if (downloader.isSaveByStreamSupported()) {
downloader.saveByServiceWorkerStream("filename")
.catch(err => {
console.error(err)
// you need to make the fallback strategy by yourself
});
} else {
// you need to make the fallback strategy by yourself
}
downloader.start();

See save-by-stream demo