【发布时间】:2021-05-22 07:23:51
【问题描述】:
我有一个员工税务档案的目录。每个文件都有一个文件名作为员工代码。我正在读取每个文件并提取一些组件并保存到一组员工对象中。
const readline = require('readline');
let empArr = [];
function readFiles(dirname) {
fs.readdir(dirname, async function (err,filenames) {
if(err) {
return err;
}
for await (file of filenames) {
const filePath = path.join(__dirname,directoryPath,file);
const readStream = fs.createReadStream(filePath);
const fileContent = readline.createInterface({
input: readStream
});
let employeeObj = {
empId : '',
TotalEarning:'',
ProfessionalTax:0,
GrossIncome:0,
isDone:false
};
fileContent.on('line', function(line) {
if(!employeeObj.empId && line.includes("Employee:")) {
const empId = line.replace('Employee: ','').split(" ")[0];
employeeObj.empId = empId;
}
else if(line.includes('Total Earnings')) {
const amount = line.replace(/[^0-9.]/g,'');
employeeObj.TotalEarning = amount;
}
else if(line.includes('Profession Tax')) {
const amount = line.split(" ").pop() || 0;
employeeObj.ProfessionalTax = amount;
}
else if(line.includes('Gross Income')) {
const amount = line.replace(/[^0-9.]/g,'');
employeeObj.GrossIncome = amount ||0;
}
else if(line.includes('finance department immediately')) {
employeeObj.isDone =true;
empArr.push(employeeObj);
}
});
fileContent.on('close', function() {
fileContent.close();
});
}
})
}
readFiles(directoryPath);
我无法获得 empArr。得到数组后,我需要保存到excel。这部分我将在获取员工对象数组后尝试。
【问题讨论】:
-
有什么问题?您无法根据您添加的条件进行读取?或者还有其他错误吗?正在读取的文件,扩展名是什么?你得到正确的数据了吗?您是否检查了即将发生的内容,包括文件路径、文件名等?
-
一条新闻是
for await (file of filenames)中的await没有做任何事情。await只在等待承诺时做一些有用的事情。 -
所以,这里的主要问题是您在
for循环中启动了一堆异步操作,它们都并行运行,您无法知道它们何时完成.因此,您无法知道empArr何时被完全填充,因此无法使用它。您正在使用的 readline 模块的接口完全是非阻塞和异步的。所以你运行你的for循环,它设置了一堆readline对象,然后你的for循环结束,然后所有readline开始触发它们的line事件。同时,您的函数已经返回。 -
@ApoorvaChikara 正在读取文件,并且employeeObj 也是正确的。只是问题是它被添加到 empArr 之后我不确定在哪里返回 empArr
-
@jfriend00 是的,当没有文件要处理时,empArr 已满。当我在 for() 循环之外尝试 console.log(empArr) 时,我得到空数组。
标签: javascript node.js async-await readline