Search⌘ K

Solution to Sub-task: Get Nested Path Name

Explore how to implement an asynchronous recursive function in JavaScript that traverses all nested directories to return a comprehensive array of file and folder paths. Understand how to combine async-await with Promise.all and array methods to handle deep directory structures efficiently.

We'll cover the following...

Get nested path names

Traverse further into directories recursively, to have an exhaustive array of paths to all files and directories, within the given directory path.

Node.js
var getNestedPathNames = async (dir) =>{
var dirNames = await getPathNames(dir);
if (dirNames.length === 0) return [];
var nestedPathPromises = dirNames
.map(x => getNestedPathNames(x));
var nestedPath = await Promise.all(nestedPathPromises);
var newPath = nestedPath.reduce((prev, curr)=> [...prev,...curr], []);
return [...dirNames, ...newPath];
}
var test = async () => {
await populate_directory(); // initialise custom directories in background
var names = await getNestedPathNames('dir'); // get nested paths
console.log(names); // print output of promise
}
test();

Use an asynchronous function by adding the async token to the function (line 1). Make use of ...