2

I want to use nodejs to create a streaming server (i know that there are a lot but i want to create one using nodejs), the problem is that the video doesn't get downloaded like on youtube, can you give how to do to get a streaming like youtube, Thank you

var http = require('http'),
var fs = require('fs'),
var util = require('util');

http.createServer(function (req, res) {
var path = '/home/flumotion/test.mp4';
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers['range']) {
    var range = req.headers.range; 
    console.log("Range = "+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);
  }
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
wanna know
  • 296
  • 3
  • 12
  • 1
    Might be worth looking at this Q&A: http://stackoverflow.com/questions/24976123/streaming-a-video-file-to-an-html5-video-player-with-node-js-so-that-the-video-c – Mick Mar 19 '15 at 10:55
  • Thank you, but controls work perfectly in my case – wanna know Mar 19 '15 at 11:06
  • Maybe I misunderstood your question but that answer contains a working example of a streaming server, I believe (have not actually tried it myself). – Mick Mar 19 '15 at 13:10
  • Yes, it does but not the same manner of youtube, requests aren't been sent each interval of time – wanna know Mar 19 '15 at 14:41
  • I think it might be good to explain the question in a bit more detail - I'm not quite sure it is clear from the question or these comments. – Mick Mar 19 '15 at 15:20

1 Answers1

0

sending 206 instead of 200 worked for me

var range = req.headers.range;
var total = data.length;// your video size.. you can use fs.statSync("filename").size to get the size of the video if it is stored in a file system 
split = range.split(/[-=]/),
ini = +split[1],
end = split[2]?+split[2]:total-1,
chunkSize = end - ini + 1;

res.writeHead(206, {
    "Content-Range": "bytes " + ini + "-" + end + "/" + total,
    "Accept-Ranges": "bytes",
    "Content-Length": chunkSize,
    "Content-Type": // check mimeType
});
zeah
  • 254
  • 4
  • 7