0

Im trying to make a program that reads all the files on your computer and put their paths inside an array. However, the function is recursive and I don't know how to log the results once the function is done.

Obviously i need some sort of callback, but I have tried several different approaches and the callback function ends up running before the result is complete. Also, I want the callback function to only run once (when the recursive function is done).

This is my code right now, how do i insert a callback function into the readAllFolders function?

const testFolder = "C:/"; 
const fs = require('fs');

function readAllFolders(path){
    var returnArr = [];
    fs.promises.readdir(path, (err, files) => {
        if(err){
            return;
        }

        files.forEach(file => {
            try{
                var filePath = path + file;
                if(fs.existsSync(filePath) && fs.lstatSync(filePath).isDirectory()){
                     readAllFolders(filePath + '/');
                }else{
                    returnArr.push(filePath);
                }
            }catch(e){

            }
        });
  });

  return returnArr;
}


var arr = readAllFolders(testFolder);
console.log(arr);

  • you need a base case so the function knows when to stop. You might want to have a hashmap to lookup wether you have already searched a directory or not. – about14sheep Jan 02 '22 at 17:06
  • I don't see how a base case would help, i only want the function to do a callback/return once every folder is searched through. – Daniel Karlsson Jan 02 '22 at 17:30
  • what is the problem then? does it just not stop? or is the return unexpected? – about14sheep Jan 02 '22 at 17:34
  • The problem is that the function will continue to run and fill up the array. The array will be logged just as the program starts, so the print out will be an empty array. I want the function to callback once every call is complete somehow. – Daniel Karlsson Jan 02 '22 at 18:16
  • the function is running but that print statement logs? if the function is running it probably does not stop because it does not have a base case to know when to stop. However, it being logged is odd, try putting a print statement in that `if (err)` to see if you are getting an error immediately. – about14sheep Jan 02 '22 at 18:22

0 Answers0