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);