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 = [];
值发送到浏览器,但第一次调用时显示为空数组,第二次调用时数组中填充了第一个调用的函数,第三次调用时数组中追加了相同的元素。
我希望内容显示在第一个。
1条答案
按热度按时间xfb7svmp1#
1.您在全局作用域中定义了
logtraceArr
,因此它永远不会被清除。如果您希望每个请求都有一个空数组-请在路由器回调中定义logtraceArr
(例如在调用readFiles
之前的行上)1.如果不执行
await
,则Promise.all()
不会等待。要等待,可以从readFiles
返回getfileContent
的结果,然后在readFiles
的结果之后发送请求。例如: