【发布时间】: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