简体   繁体   English

传输到中间 stream 时,视频没有流式传输

[英]video is not streaming when piped to a middle stream

I would like to create a basic video streaming server with usage statistics, using node.js , the video source is a local file.我想使用node.js创建一个具有使用情况统计的基本视频流服务器,视频源是本地文件。 The streaming works as expected with this:流媒体按预期工作:

fs.createReadStream("file.mp4").pipe(res);

But I would like to get some usage statistics, so I added a passThrough stream,但是我想得到一些使用统计,所以我添加了一个passThrough stream,

const stats = new PassThrough();

for the statistics I will add some code to the stats stream data event like this //stats.on('data',(chunk)=> { });对于统计数据,我将向stats stream 数据事件添加一些代码,如下所示//stats.on('data',(chunk)=> { });

But now the video is not streaming any more when I pipe it to the stats stream但是现在当我将 pipe 发送到统计数据 stream 时,视频不再流式传输

fs.createReadStream("file.mp4").pipe(stats).pipe(res);

can you tell me please what I'm missing here?你能告诉我我在这里缺少什么吗?

Still can't figure out how to put the stats middle stream and receive the video stream on res, although, one possible solution is to move the stats events listeners to the readStream like so:仍然无法弄清楚如何将 stats 放在中间 stream 并在 res 上接收视频 stream,但是,一种可能的解决方案是将 stats 事件侦听器移动到 readStream ,如下所示:

const { createReadStream, stat } = require("fs");
const { promisify } = require("util");
const fileInfo = promisify(stat);
const { size } = await fileInfo(filePath);

const { range } = req.headers;
      let start = 0;
      let end = size - 1;

      if (range) {

        start = range.replace(/bytes=/, "").split("-")[0];
        start = parseInt(start, 10);
        end = range.replace(/bytes=/, "").split("-")[1];
        end = end ? parseInt(end, 10) : size - 1;

        res.writeHead(206, {
          "Content-Range": `bytes ${start}-${end}/${size}`,
          "Accept-Ranges": "bytes",
          "Content-Length": end - start + 1,
          "Content-Type": "video/mp4",
        });
        logUpdate("range:", range);

      } else {

        res.writeHeader(200, {
          "Content-Type": "video/mp4",
          "Content-Length": size,
        });
      }

      createReadStream(filePath, { start, end })
        .on("data", dataEventHandler)
        .on("error", errorEventHandler)
        .on("close", closeEventHandler)
        .on("end", endEventHandler)
        .pipe(res);

dataEventHandler = (chunk) => {
  total += chunk.length;
  logUpdate("bytes: ", total);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM