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

How to get file size in nodejs as async await?

如何在 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();异步?或者有什么建议?

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

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

默认为回调方式。

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

要使回调方法 return 承诺,您可以这样做:

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 以供参考。

请使用 npm-multer

检查这个 link

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

var upload = multer({ 存储:存储, 限制:{ fileSize:maxSize } }).单('bestand');

答案可能不同,但会对您有所帮助。
正如您所说,您正在优化执行视频流。
所以像 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

npm i file_size_url


import file_size_url from 'file_size_url';

file_size_url("https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/001.mp3")
    .then(console.log) // 968.27 KB
    .catch(console.error);


import file_size_url from 'file_size_url';

let size = await file_size_url("https://serverjyy10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/0001.mp3")
    .catch((error) => console.log(error))

console.log(size) // 968.27 KB


lop 示例


let array = [

    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/001.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/002.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/003.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/055.mp3',
    'https://server10.mp3quran.net/bader/Rewayat-Hafs-A-n-Assem/110.mp3',

]

for (let index = 0; index < array.length; index++) {

    try {

        let fies_size = await file_size_url(array[index])

        if (fies_size.toString().split('.')[0] <= 95 && fies_size.toString().split(' ')[1] === 'MB') {

            console.log(fies_size + ' || <= 95 MB');

        }

        else if (fies_size.toString().split('.')[0] > 95 && fies_size.toString().split(' ')[1] === 'MB') {

            console.log(fies_size + ' || > 95 MB');

        }

        else if (fies_size.toString().split(' ')[1] === 'KB') {

            console.log(fies_size + ' || KB');

        }


    } catch (error) {

        console.log(error);

    }

}


/* output 
968.27 KB || KB
170.58 MB || > 95 MB
95.77 MB || <= 95 MB
12.21 MB || <= 95 MB
711.92 KB || KB
*/