Search code examples
javascriptnode.jsasync-awaites6-promise

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!


Solution

  • 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).

    Covered that and now I get results!

    Thank you!