javascript - 从文件系统创建对象树
问题描述
我需要从 CL 参数中获取目录的路径,并创建一个对象树,其中包含所选目录的文件结构。
如果它是一个文件,它的值应该是 true。如果它是一个目录,我应该对该目录做同样的事情(我认为最好的方法是递归)。
输出应如下所示:
{
file.txt: true,
directory: {
one.txt: true,
two.txt: true,
...
}
...
}
到目前为止,我尝试了它的递归版本,但它失败了,不知道为什么。我认为这是因为我没有正确处理代码的异步部分。这是我的代码:
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...");
}
})();
解决方案
您可以使用fs.promises
fs 的基于回调的方法来代替,这可以提高可读性并帮助您轻松找到错误。您正在记录从未createTree
定义的函数返回的内容。您应该记录result
对象以查看您想要的结果。
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 = async (path) => {
try {
const stats = await fs.promises.lstat(path);
return stats.isDirectory();
} catch (error) {
throw new Error("No such file or Directory");
}
};
//Recursive function that should create the object tree of the file system
const createTree = async (path, target) => {
const data = await fs.promises.readdir(path);
for (const item of data) {
const currentLocation = `${path}/${item}`;
const isDir = await isDirectory(currentLocation);
if (!isDir) {
target[item] = true;
continue;
}
target[item] = {};
await createTree(currentLocation, target[item]);
}
};
//Consuming the createTree function
(async () => {
try {
await createTree(basePath, result);
console.log(result);
} catch (error) {
console.log(error.message);
}
})();
推荐阅读
- unit-testing - 如何在 Kotlin 中对 ViewModel 进行 Mockito 单元测试
- javascript - 为什么 Array.prototype.sort 在 Chrome 中有不同的行为?
- swift - 从 Swift/MacOS 运行 shell 脚本
- django - Django rest - 路由器没有创建 url 路径,给出 404,并且 api 网页列出了不正确的 url
- python - 在 pandas 多索引中使用条件函数编辑数据
- nginx - 如何在一个托管服务提供商上托管我网站的根 URL ('/'),而在另一个托管服务提供商上托管所有其他 URL?
- typescript - 尝试以功能方式生成记录器工厂
- scala - 如何在现有的 SBT scala 项目中互操作 kotlin 代码
- google-cloud-platform - 从 GCP Firestore 导出文档所需的最低权限
- sql - SQL如何从两列中提取不同的数据