Skip to main content

Usage

Getting Started​

Copy the demo HTML file into your IDE and open it in two browser tabs to test P2P.

Register Domain​

Register your domain to activate the P2P service.

tip

Localhost is always whitelisted, so no additional configuration is needed to test locally.

Prepare​

CORS​

Make sure your file servers have proper CORS (Cross-Origin Resource Sharing) headers configured so that data can be fetched across domains.

OPTIONS REQUEST​

OPTIONS requests are required to perform RANGE requests in a cross-domain environment. In general, add the following header to the HTTP response:

Access-Control-Allow-Methods: GET, OPTIONS

RANGE REQUEST​

RANGE requests are required for P2P. Add the following header to the HTTP response:

Access-Control-Allow-Headers: Range

Some browsers, such as Firefox, require Access-Control-Expose-Headers to be set in the HTTP response header in order to read the file size:

Access-Control-Expose-Headers: Content-Length

Include​

Script​

Include the pre-built script for the latest version:

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

File​

Download here
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, require it in your player module:

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

If you're using ES6 import syntax:

import P2PEngineFile from '@swarmcloud/file';

Usage​

Create a P2PEngineFile instance, passing the url as a 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 to client-side storage or memory and then saving via a blob URL, you can now create a writable stream directly to the file system. This works by emulating how a server would instruct the browser to save a file, using response headers together with a service worker. This creates a man-in-the-middle page that installs the service worker in a secure context, hosted via an iframe on GitHub Pages. You can also host mitm.html 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 the save-by-stream demo