【问题标题】:How to get file size in nodejs as async await?如何在nodejs中获取文件大小作为异步等待?
【发布时间】:2020-05-09 11:59:21
【问题描述】:

如何在 nodejs 中获取文件大小作为异步等待?

这是使用 nodejs 进行视频流式传输的代码。 (我们正在寻找针对移动后端 API 优化执行视频流的想法)

const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();

app.get("/video", async (req, res) => {
  const path = "assets/sample.mp4";
  const stat = await fs.stat(path);  // here is the issue 
  const fileSize = stat.size;
  const range = req.headers.range;

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

    if (start >= fileSize) {
      res
        .status(416)
        .send("Requested range not satisfiable\n" + start + " >= " + fileSize);
      return;
    }

    const chunksize = end - start + 1;
    const file = fs.createReadStream(path, { start, end });
    const head = {
      "Content-Range": `bytes ${start}-${end}/${fileSize}`,
      "Accept-Ranges": "bytes",
      "Content-Length": chunksize,
      "Content-Type": "video/mp4"
    };

    res.writeHead(206, head);
    file.pipe(res);
  } else {
    const head = {
      "Content-Length": fileSize,
      "Content-Type": "video/mp4"
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

app.listen(3000, function() {
  console.log("Listening on port 3000!");
});

此代码在const stat=await fs.stat(path); 上有问题,

同步代码在这里工作正常,如const stat=await fs.statSync(path);

fs.stat();异步怎么写?或者有什么建议吗?

【问题讨论】:

    标签: node.js async-await fs stat


    【解决方案1】:

    你可以做的是 Promisify fs.stat 然后以异步方式使用它。 你可以使用这个。 util.promisify()

    要让回调方法返回 Promise,你可以这样做:

    const fs = require("fs");
    const writeFile = promisify(fs.writeFile);
    const { promisify } = require("util");
    
    async function main() {
        await writeFile("/tmp/test4.js",
            "console.log('Hello world with promisify and async/await!');");
    
        console.info("file created successfully with promisify and async/await!");
    }
    
    main().catch(error => console.error(error));
    

    您可以查看此link 以获取参考。

    【讨论】:

      【解决方案2】:

      您需要使用promisesversion 才能使用async/await。将您的要求更改为

      const fs = require("fs").promises;
      

      默认为回调样式。

      【讨论】:

      • ``` 等待 fs.stat(path); ``` UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'stat' of undefined
      • 外壳中的错字。它应该是promises 而不是Promises.. 更新答案
      • 它是promises,带有一个小p。
      • 它工作得很好! fs.createReadStream() 不适用于 require("fs").promises !
      • 这是正确的答案,但问题不是如何获得 fs,而是如何获得大小。完整的答案是:``` const fs = require("fs").promises;让 size = (await fs.stat(path)).size ```
      【解决方案3】:

      可能会有所不同,但会对您有所帮助。
      正如您所说,您正在优化执行视频流。
      所以像youtube这样的网站使用UDP而不是TCP。您可以了解 UDP Here
      如果您使用的是 node js,那么您可以使用套接字来实现它

      io.on('connection', function (socket) {
      
          console.log('Socket connected: '+socket);   
          io.sockets.emit('msgFromAdmin', 'Hello client, this message sent from admin');
          // call our main handler 
          streamer(socket);
      
      }); 
      
      /*
      initializes ffmpeg child process which will listen on udp port:33333 for incoming frames of stream
      forward video stream to client.html through socket.io
      */
      var streamer = function (socket) {  
      
          var ffmpeg = require('child_process').spawn("/vagrant/nodejs-ffmpeg-livestreamer/ffmpeg-source/ffmpeg", ["-re","-y","-i", "udp://127.0.0.1:33333", "-f", "mjpeg", "-s","500x500","-pix_fmt","rgb24","pipe:1"]);
      
          ffmpeg.on('error', function (err) {
              console.log(err);
          });
      
          ffmpeg.on('close', function (code) {
              console.log('ffmpeg exited with code ' + code);
          });
      
          ffmpeg.stderr.on('data', function (data) {
              console.log('stderr: ' + data);
          });
      
          ffmpeg.stdout.on('data', function (data) {
      
              var frame = new Buffer(data).toString('base64');
              socket.emit('render',frame);
          });
      
      };
      

      没有时间写代码所以这是从网上复制的代码


      如需完整代码,您可以访问Here

      【讨论】:

        【解决方案4】:

        请使用 npm-multer

        查看此链接

        https://www.npmjs.com/package/multer

        var 上传 = multer({ 存储:存储, 限制:{文件大小:最大大小} }).single('bestand');

        How to limit the file size when uploading with multer?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-30
          • 2020-07-11
          • 2020-03-31
          • 1970-01-01
          • 2019-07-20
          • 2015-12-21
          • 1970-01-01
          相关资源
          最近更新 更多