I need to get the path of the directory from the CL argument and and create an object tree, which contains the file structure of the selected directory.
If it's a file, it's value should be true. And if it's a directory I should do the same for that directory (I think the best approach is recursion).
The output should look like something like this:
{
file.txt: true,
directory: {
one.txt: true,
two.txt: true,
...
}
...
}
So far I tried the recursion version of that but it fails and don't know why. I think it's because I didn't handle the async part of my code properly. Here is my code:
const fs = require("fs");
const basePath = process.argv[2]; //Getting the path (it works)
const result = {};
//Function to check my path is exist and it's a directory
const isDirectory = path => {
return new Promise((resolve, reject) => {
fs.lstat(path, (err, stats) => {
if (err) reject("No such file or Directory");
resolve(stats.isDirectory());
});
});
};
//Recursive function that should create the object tree of the file system
const createTree = (path, target) => {
return new Promise((resolve, reject) => {
reject("Promise Oops...");
fs.readdir(path, (err, data) => {
data.forEach(item => {
const currentLocation = `${path}/${item}`;
isDirectory(currentLocation)
.then(isDir => {
if (!isDir) {
target[item] = true;
return;
}
target[item] = {};
resolve(createTree(currentLocation, target[item]));
})
.catch(err => console.log("Oops in then..."));
});
});
});
};
//Consuming the createTree function
(async () => {
try {
const res = await createTree(basePath, result);
console.log(res);
} catch (err) {
console.log("Oops consume...");
}
})();