My current function implementation looks like this:
function populateMap(directory: string, map, StringMap) {
fs.promises.readdir(directory).then(files: string[]) => {
files.forEach(file: string) => {
const fullPath = path.join(directory, file);
fs.stat(fullPath, (err: any, stats: any) => {
if (stats.isDirectory()) {
populateFileMap(fullPath, fileMap);
} else {
fileMap[file] = fullPath;
}
});
});
});
}
The goal is to recursively traverse the parent directory and create a map of file names to their paths. This seems to be functioning correctly as confirmed by the populated fileMap when I log it after the deepest file in the directory.
In the calling function, I need to have access to the complete map:
function populateMapWrapper(dir: string) {
const fileMap: StringMap = {};
populateMap(dir, fileMap);
// At this point, fileMap should contain all the necessary data
}
I attempted to make populateMap asynchronous by adding a .then() method when called in the wrapper function. However, when I log fileMap within the then() block, it appears to be empty.
I am uncertain whether this issue stems from how JavaScript handles variables or if there is a gap in my understanding of promises. I am open to exploring alternative methods to achieve the desired outcome.