I am developing an online course application. Once a user is enrolled in a course, then that user can go to the home page of course, and then click on any video lecture to view it. To stream video which is in .mp4 format, I am using socket.io. Here is what i'm doing right now.
router.get('/learn/:courseName/lecture/:video', isAuthenticated, function (req, res) {
// var file = path.resolve(__dirname,"movie.mp4");
console.log('courseName is: ' + req.params.courseName);
console.log('video name is: ' + req.params.video);
var file = "/home/mobileedx/WebstormProjects/passportAuthentication/videoLecture/movie.mp4";
console.log('file is: ' + file);
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
console.log('value of range is: ' + range);
if(!range) {
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
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);
});
console.log('stream value is: ' + stream);
});
});
However when I try to access it from browser, I get an error in the browser as "Range not Satisfiable". I am using google chrome and mozilla firefox for testing.
I'm logging the req.headers.range and I get its value as 'undefined'.
Here it is.
Here is the request and response header, when we access it through browser. You can notice, there is no 'Range' header in the GET request.
Please let me know, what's going wrong here. Because, If I run the same code as a standalone application, then it works.