I want to use then()
, as seen below, after my code has finished recursing the folder hierarchy.
Everything works great, particularly the use of
const fileNames = await fs.promises.readdir(dir);
and
const stat = await fs.promises.stat(thing_path);
However, the recursive part I do not know how to implement correctly so that
getFolderInfo(start).then((all_data)=>{
console.log('Done recursing the directory');
});
works correctly.
Complete File
const fs = require('fs');
const path = require('path');
// Configure & Initialize
let start = '_t/';
let depth = 1;
let counter = 0;
let total_size = 0;
// Definition
async function recurseFolders(dir, callback) {
const fileNames = await fs.promises.readdir(dir);
const listings = await Promise.all(
fileNames.map(async (thing_name) => {
const thing_path = path.join(dir, thing_name);
const stat = await fs.promises.stat(thing_path);
return {name: thing_name, path: thing_path, size: stat.size, isFolder: stat.isDirectory()};
})
);
listings.forEach(iterate);
function iterate (listing) {
counter++;
total_size += listing.size;
listing.counter = counter;
listing.total_size = total_size;
callback(listing);
if (listing.isFolder) {
recurseFolders(listing.path, callback);
}
}
}
async function getFolderInfo (start) {
await recurseFolders(start, (data) => {
console.log(data);
});
}
getFolderInfo(start).then((all_data)=>{
console.log('Done recursing the directory');
});