Node.js: how to stream a mp4 file


How to stream a mp4 file with Node.js

var http = require('http'),
    fs = require('fs'),
    util = require('util');
var serverFunction = function (req, res) {
  var path = '/relative/path/of/mp4/file.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);
  }
}
http.createServer(serverFunction).listen(31000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:31000/');

Run test

$ node app.js
Server running at http://127.0.0.1:31000/
ALL: 342123568
RANGE: 0 - 342123567 = 342123568
ALL: 342123568
RANGE: 57933824 - 342123567 = 284189744
RANGE: 148668416 - 342123567 = 193455152
RANGE: 247431168 - 342123567 = 94692400
RANGE: 293732352 - 342123567 = 48391216
...

nodejs stream

Note: fs.statSync will throw an error if file not exists:

Error: ENOENT: no such file or directory

So, you should use try catch clause to catch this error:

    try{
      var stat = fs.statSync(path);
...
    }catch(e){
        //handle error
    }

Leave a Reply