Home > Blockchain >  Get the number of Requests in Express with Save
Get the number of Requests in Express with Save

Time:05-04

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`);
});

CodePudding user response:

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-

CodePudding user response:

use this one for this logic, First request = 1 Times and Second Request = 11 is add 1 on back not like 1 1 but like 1,1,1,1,1.

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