[英]NodeJS: Searching for specific string with fs.readFile() on multiple files
I have an array of objects, each one is a file with properties name, path, extension, and so on, like this:我有一个对象数组,每个对象都是一个具有名称、路径、扩展名等属性的文件,如下所示:
module.exports = {
logpath: "C:\\",
logsfiles: [
{
name: "log1", // file name
path: this.logpath, // path to log
extension: ".log", // log extension
type: "server", // component type (server, connector-hub, connector-component, gateway)
licensed: true, // boolean for license holder
iis: false, // boolean for iis exposure
application: "N/A" // solution
},
{
name: "log2", // file name
path: this.logpath, // path to log
extension: ".log", // log extension
type: "server", // component type (server, connector-hub, connector-component, gateway)
licensed: true, // boolean for license holder
iis: false, // boolean for iis exposure
application: "N/A" // solution
}
]
}
And I need to iterate through this list by reading the entire file, search for a specific string and, if this string exists, store some of the file properties into an array.我需要通过读取整个文件来遍历这个列表,搜索一个特定的字符串,如果这个字符串存在,将一些文件属性存储到一个数组中。
What I have so far is this:到目前为止,我所拥有的是:
function getFile(log) {
return new Promise((resolve, reject) => {
fs.readFile(
logConfig.logpath + log.name + log.extension,
"utf8",
(err, data) => {
if (err) {
console.log(`Error reading file ${log.name}`);
reject(err);
} else {
if (data.indexOf("String pattern to search") != -1)
resolve({ name: log.name, componentkey: "TODO" });
}
}
);
});
}
I know this piece of code is working if I call it standalone.如果我将其称为独立代码,我就知道这段代码可以正常工作。 But if I try to call it inside of a loop like this:但是,如果我尝试在这样的循环中调用它:
async function getAllFiles(logs) {
const finalArray = [];
const promises = logs.map(async log => await getFile(log));
const results = await Promise.all(promises);
finalArray.push(results);
console.log(finalArray); //not printing
console.log("Done"); //not printing
}
Nothing happens... The last two prints doesn't show on the console...什么都没有发生......最后两个打印没有显示在控制台上......
Can anyone help me by showing me what am I doing wrong?任何人都可以通过向我展示我做错了什么来帮助我吗?
Noob with promises here, sorry... :) And many thanks in advance!菜鸟在这里做出承诺,对不起... :) 非常感谢!
Ah!啊! Got it!知道了!
Stupid!愚蠢的!
The getFile(log)
return promise was not resolving all of the items since I didn't had an else
statement to the if (data.indexOf("String pattern to search") != -1)
. getFile(log)
返回承诺没有解决所有项目,因为我没有对if (data.indexOf("String pattern to search") != -1)
的else
语句。
Covered that and now I get results!涵盖了这一点,现在我得到了结果!
Thank you!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.