Search code examples
node.jsasync-awaitfsstat

How to get file size in nodejs as async await?


How to get file size in nodejs as async await ?

Here is the code for video streaming with nodejs . (and we are looking optimized performing video streaming idea's for mobile back-end 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!");
});

This code have an issue on const stat=await fs.stat(path); ,

The synchronizes code working fine here like const stat=await fs.statSync(path);

how to write the fs.stat(); asynchronous ? Or any suggestions ?


Solution

  • You need to use promisesversion to use async/await. change your require to

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

    The default is callback style.