Skip to content

Instantly share code, notes, and snippets.

@thanhtoan1196
Created January 18, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thanhtoan1196/36ebe18c5c14a13b7606bb328fa2e5e4 to your computer and use it in GitHub Desktop.
Save thanhtoan1196/36ebe18c5c14a13b7606bb328fa2e5e4 to your computer and use it in GitHub Desktop.
A node js server which streams mkv to just mkv supported browsers

Setup

Get nodejs from Node

To run

node server.js

Other stuff

Have a stream.mkv file on the same path where the server is.

<html>
<title>Stream a mkv file</title>
<body>
<video id="video" src="stream.mkv" width="400" type="video/x-matroska" controls></video>
</body>
</html>
var fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
let indexPage, stream_mkv;
// load the video files and the index html page
fs.readFile(path.resolve(__dirname,"stream.mkv"), function (err, data) {
if (err) {
throw err;
}
stream_mkv = data;
console.log(stream_mkv.length);
console.log("stream_mkv.length");
});
fs.readFile(path.resolve(__dirname,"index.html"), function (err, data) {
if (err) {
throw err;
}
indexPage = data;
});
// create http server
http.createServer(function (req, res) {
var reqResource = url.parse(req.url).pathname;
//console.log("Resource: " + reqResource);
if(reqResource == "/"){
//console.log(req.headers)
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(indexPage);
res.end();
} else if (reqResource == "/favicon.ico"){
res.writeHead(404);
res.end();
} else {
var total;
if(reqResource == "/stream.mkv"){
total = stream_mkv.length;
}
var range = req.headers.range;
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
// if last byte position is not present then it is the last byte of the video file.
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end-start)+1;
if(reqResource == "/stream.mkv"){
res.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type":"video/x-matroska"});
res.end(stream_mkv.slice(start, end+1), "binary");
}
}
}).listen(8888);
@JBarmentlo
Copy link

x-matroska (i.e .mkv) doesn't work on firefox and causes a Cannot play media. No decoders for requested formats: video/x-matroska.
The format is handled by chrome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment