4

我正在编写一个程序,它将流式传输当前正在下载到驱动器上的视频文件。我遇到的问题似乎是让浏览器实际播放视频。该脚本侦听文件更改,然后流式传输其余部分,但浏览器除了显示空白视频页面外不执行任何操作。

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/');
4

1 回答 1

2

所以这个答案取决于日益增长的文件,理论上它可以满足你的需求。我担心的是该项目已经两年没有提交,所以我不知道它是否仍然有效。话虽如此,这在本地对我有用(尽管我没有测试到视频文件的管道):

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);
于 2013-02-06T23:15:09.267 回答