Thursday, 25 May 2017

How can I modify this .mp4 serving function to not need the range header?

A while back I found this function in some tutorial for streaming video so that the whole file doesn't need to be loaded into RAM for the file to be served (so you can serve big video files without crashing due to exceeding the memory cap of Node.js).

var fs = require('fs'), 
    http = require("http"), 
    url = require("url"), 
    path = require("path");
var dirPath = process.cwd();
var videoReqHandler = function(req, res, pathname) {
    var file = dirPath + "/client" + pathname;
    var range = req.headers.range;
    var positions = range.replace(/bytes=/, "").split("-");
    var start = parseInt(positions[0], 10);
    fs.stat(file, function(err, stats) {
        if (err) {
            throw err;
        } else {
            var total = stats.size;
            var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
            var chunksize = (end - start) + 1;
            res.writeHead(206, {
                "Content-Range" : "bytes " + start + "-" + end + "/" + total,
                "Accept-Ranges" : "bytes",
                "Content-Length" : chunksize,
                "Content-Type" : "video/mp4"
            });
            var stream = fs.createReadStream(file, {
                start : start,
                end : end
            }).on("open", function() {
                stream.pipe(res);
            }).on("error", function(err) {
                res.end(err);
            });
        }
    });
};
module.exports.handle = videoReqHandler;

It works fine in Chrome and FF, however, when Internet Explorer, or Edge, if you will, (new name, same pathetic feature support) requests an mp4, it crashes the server. I suspect that's because of this.

My question is, how can I modify this function to avoid crashing when the range header isn't sent? I don't know much about headers or video streaming, and wouldn't have the slightest clue how to rewrite this function without some sort of demonstration.



via Viziionary

No comments:

Post a Comment