Get nodejs from Node
node server.js
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); |
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.