Search code examples
javascriptnode.jsejs

Get the number of Requests in Express with Save


I would like to know if is there any way of getting the total number of request in a certain path with Expressjs? But i need save On JSON like i want save data on JSON or TXT nothing more but i dont know how.

let pingCount = "HERE I MUST ADD Some JS for save on TXT/JSON file and show data if you give request write on JSON +1"
app.get('/ping',(req, res) => {
  pingCount++;
  res.send(`ping world for ${pingCount} times`);
});

Solution

  • import { readFileSync, writeFileSync } from "fs";
    app.get('/ping',(req, res) => {
        const pingCount = readFileSync("pingCount.txt");
        const newPingCount = parseInt(pingCount) + 1;
        writeFileSync("pingCount.txt", newPingCount.toString());
        res.send(`ping world for ${newPingCount} times`);
    });
    

    This should work, but create a pingCount.txt file with text 0 first-