我有一个对象数组,每个对象都是一个具有属性名称、路径、扩展名等的文件,如下所示:
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
}
]
}
我需要通过读取整个文件来迭代此列表,搜索特定字符串,如果该字符串存在,则将一些文件属性存储到数组中。
到目前为止我所拥有的是:
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" });
}
}
);
});
}
如果我将其称为独立的,我知道这段代码是有效的。但如果我尝试在循环内调用它,如下所示:
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
}
什么也没发生...最后两个打印没有显示在控制台上...
任何人都可以帮助我告诉我我做错了什么吗?
菜鸟在这里做出 promise ,抱歉...:) 提前非常感谢!
最佳答案
啊!明白了!
愚蠢!
getFile(log)
返回 promise 无法解析所有项目,因为我没有针对 if (data.indexOf (“要搜索的字符串模式”)!= -1)
。
涵盖了这一点,现在我得到了结果!
谢谢!
关于javascript - NodeJS : Searching for specific string with fs. readFile() 多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916358/