Skip to content

Instantly share code, notes, and snippets.

@mlzxy
Last active June 3, 2020 17:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mlzxy/1c04315372901a2822537074da06647f to your computer and use it in GitHub Desktop.
Save mlzxy/1c04315372901a2822537074da06647f to your computer and use it in GitHub Desktop.
Node.js Static File + Media Streaming Server
/**
* 1. install nodejs from https://nodejs.org/en/download/
* 2. run `npm install -g serve-static filehandler serve-index` in terminal
* 3. run `node mediaserver.js`
*/
var http = require('http'),
fs = require('fs'),
util = require('util'),
url = require('url'),
path = require('path'),
serveStatic = require('serve-static'),
finalhandler = require('finalhandler'),
ip = require('ip');
var serveIndex = require('serve-index')
var port = 1337;
var serve = serveStatic(__dirname + '/');
var index = serveIndex(__dirname + '/', {
'icons': true
});
function returnMedia(fpath, req, res, stat) {
var total = stat.size;
var ext = path.extname(fpath).slice(1);
if (req.headers['range']) {
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total - 1;
var chunksize = (end - start) + 1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' +
chunksize);
var file = fs.createReadStream(fpath, {
start: start,
end: end
});
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end +
'/' + total,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/' + ext
});
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, {
'Content-Length': total,
'Content-Type': 'video/' + ext
});
fs.createReadStream(fpath).pipe(res);
}
}
http.createServer(function(req, res) {
if (req.url == '/index.html' || req.url == '/') {
console.log(req.url);
return index(req, res, finalhandler(req, res));
} else {
var urlParts = url.parse(req.url, true);
var fpath = decodeURIComponent(urlParts.pathname.slice(1));
try {
var stat = fs.statSync(fpath);
} catch (err) {
console.log(err);
return
}
if (stat.isDirectory()) {
return index(req, res, finalhandler(req, res));
} else {
switch (path.extname(fpath)) {
case '.avi':
case '.webm':
case '.gif':
case '.ogg':
case '.ogv':
case '.mov':
case '.mp4':
case '.rmvb':
case '.m4v':
case '.mkv':
return returnMedia(fpath, req, res, stat);
default:
return serve(req, res, finalhandler(req, res));
}
}
}
}).listen(port, "0.0.0.0", function() {
console.log('Server running at http://' + ip.address() + ':' +
port + '/');
});
@phanirithvij
Copy link

I want to stream an mkv in firefox any ideas?
I know it can be done using FFmpeg to pipe it to an rstp:// or rtmp://.
But I want to create a m3u8 stream.

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