2013-02-06 68 views
2

我正在編寫一個程序,它將流式傳輸當前正在下載到驅動器上的視頻文件。我遇到的問題似乎是讓瀏覽器實際播放視頻。該腳本會監聽文件更改,然後將剩下的流進行流式傳輸,但瀏覽器除了顯示空白視頻頁面外不會執行任何操作。NodeJS - 正在下載的流視頻

var fs   = require('fs'), 
    http  = require('http'), 
    filename = '/home/qrpike/Videos/topgears.mp4'; 

http.createServer(function (req, res) { 

    console.log(req.url); 
    if(req.url == '/video.mp4'){ 

     res.writeHead(200,{ 
      'Content-Type'   : 'video/mp4', 
      'Cache-Control'   : 'public', 
      'Connection'   : 'keep-alive', 
      'Content-Disposition' : 'inline; filename=topgears.mp4;', 
      'Content-Transfer-Encoding' : 'binary', 
      'Transfer-Encoding'  : 'chunked' 
     }); 

     fs.open(filename, 'r', function(err, fd) { 

      if (err) throw new Error('Could not open file'); 
      var position = 0; 

      fs.stat(filename, read); 
      fs.watchFile(filename, read.bind(null, null)); 

      function read(err, stat) { 

       var delta = stat.size - position; 
       if (delta <= 0) return; 

       fs.read(fd, new Buffer(delta), 0, delta, position, function(err, bytes, buffer) { 

        console.log("err", err, "bytes", bytes, "position",position,"delta",delta); 
        res.write(buffer.toString('binary')); 

       }); 

       position = stat.size; 

      } 

     }); 

    } 

}).listen(1337); 
console.log('Server running at http://127.0.0.1:1337/'); 

回答

2

所以這個答案取決於growing-file,這在理論上你想要做什麼。我擔心這個項目在兩年內沒有提交,所以我不知道它是否仍然有效。這就是說,這對我本地工作(雖然我沒有測試管道到視頻文件):

var fs = require('fs'); 
var http = require('http'); 
var GrowingFile = require('growing-file'); 

var FILENAME = '/home/dave/Desktop/video/video.ogg'; 

var server = http.createServer(function(req, res) { 
    var file; 
    if (req.url === '/video.ogg') { 
    res.writeHead(200, { 
     'Content-Type': 'video/ogg' 
    }); 
    file = GrowingFile.open(FILENAME); 
    file.pipe(res); 
    } else { 
    res.statusCode = 404; 
    res.end('Not Found'); 
    } 
}); 

server.listen(1337);