简体   繁体   中英

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. 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,

const stats = new PassThrough();

for the statistics I will add some code to the stats stream data event like this //stats.on('data',(chunk)=> { });

But now the video is not streaming any more when I pipe it to the stats 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:

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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