3

I'm trying to set up a web server that will support streaming video to an HTML5 video tag using node.js.

Inspired from this gist

node.js code:

exports.getTrailer = function (req, res, next) {
    var path = config.rootContentFilesPath + '/movie.mp4';
    var stat = fs.statSync(path);
    var total = stat.size;
    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(path, { start: start, end: end });
        res.writeHead(206, {
            'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
            'Accept-Ranges': 'bytes',
            'Content-Length': chunksize,
            'Content-Type': 'video/mp4'
        });
        file.pipe(res);
    } else {
        console.log('ALL: ' + total);
        res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
        fs.createReadStream(path).pipe(res);
    }
};

HTML5 code:

<video src="http://localhost:3000/getTrailer" controls>
    <!-- fallback -->
    Your browser does not support the
    <code>video</code> element.
</video>

Problem: I tested the above code in chrome, it works but is not consistent. On refreshing the browser again and again, i found out that video gets played sometime where sometimes it doesn't. Can anyone help in resolving this issue.

Kunal Kapadia
  • 3,223
  • 2
  • 28
  • 36
  • 1
    Related question: http://stackoverflow.com/questions/24976123/streaming-a-video-file-to-an-html5-video-player-with-node-js-so-that-the-video-c in case others stumble upon this question from google like I did –  Apr 05 '17 at 11:27

0 Answers0