Skip to content

Instantly share code, notes, and snippets.

@edysmp
Created May 15, 2018 18:13
Show Gist options
  • Save edysmp/6bbbb0ccfa6b8ddc53327b90361a49f7 to your computer and use it in GitHub Desktop.
Save edysmp/6bbbb0ccfa6b8ddc53327b90361a49f7 to your computer and use it in GitHub Desktop.
NodeJS - Create a video streaming server
const express = require('express');
const fs = require('fs');
const app = express();
app.get('/video', function(req, res) {
const path = '/your/path/to/video-file.mp4';
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/mp4',
}
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment