Home > Net >  Array is duplicated on every refresh using ExpressJS and NodeJS
Array is duplicated on every refresh using ExpressJS and NodeJS

Time:12-08

var express = require("express");
var router = express.Router();
const fs = require("fs");
const path = require("path");
const readline = require('readline');
const directoryPath = path.resolve(__dirname,"../logtrace-filestore/edepoze-logs");
var logtraceArr = [];
router.get("/",function(req,res,next){
    const fetchFileContentParsed = async (fileContentObj) => {
     
        var logtraceObj = {
            Direction : '',
            FromServer: '',
            ToServer:''
          };
        var pipearray = fileContentObj.toString().split("|");
                for( i=0;i<pipearray.length;i  ){
                    var Direction = new Array();
                    Direction = pipearray[5].split("::");
                    if (Direction.length == 2) {
                        logtraceObj.Direction = Direction[1];
                    } else {
                        logtraceObj.Direction = "";
                    }
      
                }
                logtraceArr.push(logtraceObj);
  
        return {
            logtraceArr
          }
    }
    // Iterates all users and returns their Github info.
    const getfileContent = async (files) => {
            const fileContent = files.map((file) => {
                const filePath = path.join(directoryPath,file);
                //console.log("filePath ----->",filePath);
                const readStream =  fs.createReadStream(filePath);
                const fileContent = readline.createInterface({
                input: readStream
                });
                fileContent.on('line', function(line) {
                    const regExp = /\[Event([^] \])/g
                    var matchedContent;
                    if ((matchedContent = line.match(regExp)) != null){
                        return fetchFileContentParsed(matchedContent) // Async function that fetches the user info.
                    .then((a) => {return a })
                    }
                })
            })
            return Promise.all(fileContent) // Waiting for all the requests to get resolved.
    }
    function readFiles(dirname) {
        //console.log(dirname);
        fs.readdir(dirname, async function (err,filenames)
            getfileContent(filenames).then((a) => {return a })
        });
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.contentType('application/json');
    //console.log(readFiles(directoryPath))
    readFiles(directoryPath,logtraceArr);
    res.send(logtraceArr);
});
module.exports = router;

I have been trying to send the var logtraceArr = []; value to the browser using Expressjs but one first call empty array is displayed on 2nd call array is filled with first called function and on 3rd call array is appended with the same element.

I want the content to be displayed on the first.

CodePudding user response:

Try to return from readdir callback:

res.header('Access-Control-Allow-Origin', '*');
  res.contentType('application/json');

  fs.readdir(directoryPath, async function (err, files) {
    if (err) return res.send('Error');
    await getfileContent(files)
    res.send(logtraceArr);
  });

CodePudding user response:

  1. You define logtraceArr in the global scope, so it never will be cleared. If you want to have an empty array for each request - define logtraceArr inside the router callback (for example on the line before calling readFiles)
  2. Promise.all() doesn't wait if you don't await it. To wait you can return result of getfileContent from readFiles and then send request after result of readFiles. Fof example:

    async function readFiles(dirname) {
        fs.readdir(dirname, async function (err,filenames)
            await getfileContent(filenames).then((a) => {return a })
        });
        return
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.contentType('application/json');
    readFiles(directoryPath,logtraceArr).then(() => res.send(logtraceArr));
    

  • Related