javascript - NodeJS : Searching for specific string with fs. readFile() 多个文件

标签 javascript node.js async-await es6-promise

我有一个对象数组,每个对象都是一个具有属性名称、路径、扩展名等的文件,如下所示:

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/

相关文章:

c# - 无法在 LINQPad 中使用异步/等待 - "Invalid token {after async} in .."

javascript - 将异步并行请求映射到它们的 ID

javascript - 将javascript变量分配给jsp代码?

javascript - 如何通过 Ajax 调用 Controller 函数传递 Joomla 表单数据

javascript - 处理付款处理成功但数据库更新失败

.net - TPL 数据流 : What's the difference between these 2 code snippets?

javascript - 使用回调

javascript - Node 异步未运行异步

node.js - 如何将 HTTP 流转换为 HTTPS?

node.js - 无法在 high sierra 上完全卸载 Node 和 npm