Skip to content

Instantly share code, notes, and snippets.

@amalantony
Created March 9, 2017 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalantony/81d3ff3b4c1a26da785c0639b7808802 to your computer and use it in GitHub Desktop.
Save amalantony/81d3ff3b4c1a26da785c0639b7808802 to your computer and use it in GitHub Desktop.
app.get('/stream', (req, res) => {
const pathToVideo = "/path/to/video";
fs.stat(pathToVideo, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
console.log('File not found!');
return res.sendStatus(404);
}
res.end(err);
}
const range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
const positions = range.replace(/bytes=/, "").split("-");
const start = parseInt(positions[0], 10);
const total = stats.size;
const end = positions[1] ? parseInt(positions[1], 10) : total - 1;
const chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mkv"
});
const stream = fs.createReadStream(pathToVideo, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment