3

I'm trying to stream videos to an html5 video player using nodejs and express. Many people have done this before from what I can find, however very few have used express (in what I've found).

Most say to do this:

var express = require('express');
var request = require('request');
var stylus  = require('stylus');
var fs      = require('fs');
var path    = require('path');
var url     = require('url');
var http    = require('http');

var app = express();

app.use(stylus.middleware({
 // Source directory
     src: __dirname + '/assets/stylesheets',
     // Destination directory
     dest: __dirname + '/public',
     // Compile function
     compile: function(str, path) {
       return stylus(str)
         .set('filename', path)
         .set('compress', true);
         }
     }));

app.enable('trust proxy');
// Routing to the user
app.use(express.static(__dirname + "/public"));

var server = require('http').createServer(app);
// var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

server.listen(port, function() {
    console.log("Server is listening on port " + port.toString());
});


app.post('/playVideo', function(req, res) {

    var video = req.query.video;

    var file = path.resolve(__dirname,video);
    var range = req.headers.range;


    var positions = range.replace(/bytes=/, "").split("-");
    var start = parseInt(positions[0], 10);

    fs.stat(file, function(err, stats) {
      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/avi"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
});

Unfortunately, when I attempt to do this I am unable to get the req.headers object. It's undefined. I assume this is because I'm using Express, although I have to assume that it's still possible with Express.

How can I get the header using express?

Thanks!

Jake Alsemgeest
  • 626
  • 2
  • 12
  • 23

1 Answers1

0

I think you should use middleware body-parser

Here is the example:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
BlackMamba
  • 9,026
  • 6
  • 36
  • 58