I built a small website that moves photos and videos between an iPhone and an Android phone. No app, no upload to a server: the file goes straight from one browser to the other over WebRTC.
Connecting the two phones was the easy part. Sending a 1 GB video without crashing the tab was not. Here are the three problems I hit, and the small library I made from the solution.
Problem 1: you can't send a whole file at once
A data channel message has a size limit, so the file has to be cut into pieces. I use 64 KB pieces. I also read the file from disk 1 MB at a time with file.slice(), so the whole video never sits in memory on the sending side.
Problem 2: the buffer fills up
channel.send() doesn't wait. If you call it in a loop, everything goes into bufferedAmount, memory grows, and on a phone the tab can die. The fix is to stop when the buffer is too full and continue when it drains:
if (channel.bufferedAmount > 8 * 1024 * 1024) { await new Promise((resolve) => { channel.bufferedAmountLowThreshold = 1024 * 1024; channel.addEventListener('bufferedamountlow', resolve, { once: true }); }); } channel.send(chunk); (Some browsers sometimes miss that event, so the library also checks on a timer.)
Problem 3: "sent" doesn't mean "received"
When the last send() finishes, the data may still be in the buffer. So the receiver sends back a small "got it" message, and only then do I show "Sent ✓".
The library
I put all of this into datachannel-file-transfer: one file, no dependencies.
import { createFileTransfer } from 'datachannel-file-transfer'; const transfer = createFileTransfer(channel, { onProgress: (p) => console.log(p.direction, p.name, p.bytes, '/', p.total), onFile: (file) => console.log('received', file.name) }); await transfer.sendFile(file); // resolves when the other side has it It works in both directions on the same channel, and with PeerJS, simple-peer or your own signaling.
- npm: https://www.npmjs.com/package/datachannel-file-transfer
- GitHub: https://github.com/besimobai/datachannel-file-transfer
This is my first open-source package. If you try it, I'd love to hear what breaks.
![Locomotion Balance and Motion Control — Ch.11: Case Studies [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvkkda1tl380kl4y7zvly.png)
![Locomotion Balance and Motion Control — Ch.12: Checklists and Templates [EN]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnsx5xe4pqm4xo5p6kb4t.png)