const path = require('path'); const url = require('url'); const express = require('express'); const fs = require('fs'); const http = require('http'); const io = require('socket.io'); const app = express(); const port = 8443; const server = http.createServer(app).listen(port, function() { console.log('Open http://localhost:' + port + '/ with a browser'); }); // CORS app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.use(express.static(path.join(__dirname, 'static'))); const socket = io(server); let blobs = []; socket.on('connection', (socket) => { console.log('Connected ' + socket.id); socket.on('error', (error) => { console.error('Connection ' + socket.id + ' error', error); }); socket.on('disconnect',(socket) => { console.log('Connection ' + socket.id + ' closed'); }); socket.on('blob', (data) =>{ console.log('new blob'); // Send via socket socket.broadcast.emit('newBlob', data); // Save to file fs.appendFileSync('new.webm', data); }); }); app.get('/video', function(req, res) { const path = 'new.webm' const stat = fs.statSync(path) const fileSize = stat.size; const range = req.headers.range; if (range) { const parts = range.replace(/bytes=/, "").split("-"); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize-1 const chunksize = (end-start)+1; const file = fs.createReadStream(path, {start, end}); const head = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/webm', } res.writeHead(206, head); file.pipe(res); } else { const head = { 'Accept-Ranges': 'bytes', 'Content-Length': fileSize, 'Content-Type': 'video/webm', } res.writeHead(200, head) fs.createReadStream(path).pipe(res) } })