使用ExpressJS和NodeJS在每次刷新时复制数组

mccptt67  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(107)
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;

我一直试图使用Expressjs将var logtraceArr = [];值发送到浏览器,但第一次调用时显示为空数组,第二次调用时数组中填充了第一个调用的函数,第三次调用时数组中追加了相同的元素。
我希望内容显示在第一个。

xfb7svmp

xfb7svmp1#

1.您在全局作用域中定义了logtraceArr,因此它永远不会被清除。如果您希望每个请求都有一个空数组-请在路由器回调中定义logtraceArr(例如在调用readFiles之前的行上)
1.如果不执行await,则Promise.all()不会等待。要等待,可以从readFiles返回getfileContent的结果,然后在readFiles的结果之后发送请求。例如:

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

相关问题