title: Video Streaming with HTML5 using express.js
body: <p>I'm trying to set up a web server that will support streaming video to an HTML5 video tag using node.js.</p>
  
  <p>Inspired from this <a href="https://gist.github.com/paolorossi/1993068" rel="nofollow">gist</a></p>
  
  <p><strong>node.js code:</strong></p>
  
  <pre><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);
      }
  };
  </code></pre>
  
  <p><strong>HTML5 code:</strong></p>
  
  <pre><code>&lt;video src="http://localhost:3000/getTrailer" controls&gt;
      &lt;!-- fallback --&gt;
      Your browser does not support the
      &lt;code&gt;video&lt;/code&gt; element.
  &lt;/video&gt;
  </code></pre>
  
  <p><strong>Problem:</strong>
  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.</p>