0

I could use help returning an object created from reading files in a folder and saving their hash values and name to an object.

checkHashedFolder(dir1, dir2) {
  const directory1 = dir1.replace(/@@@@@/g, '/');
  const directory2 = dir2.replace(/@@@@@/g, '/');
  var hashedFolder = [];
  fs.readdir(directory1, function(err, files) {
    if (err) {
      console.error("Could not list the directory.", err);
    }
    files.forEach(function(file, index) {
      let newPath = path.join(directory1, file);
      return fs.readFile(`${newPath}`, 'utf8', function(err,data) {
        if (err) {
          return console.log(err);
        }
        hashedFolder.push({
          name: file,
          hash: data
        });
        return hashedFolder;
      });
    });
    return hashedFolder;
  });
}

I know the object is being built how I would like it to because i've logged it. I just don't know how to return the object that is being created. Thanks.

  • 1
    Think asynchronously; you cannot return, but you can pass a callback. Or you can use `async/await`. – elclanrs Dec 09 '17 at 23:11
  • [**Similar problem**](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). **Note:** that in your case you have two levels of asynchronous functions: `readdir > readFile`. – ibrahim mahrir Dec 09 '17 at 23:13

0 Answers0