Node.js折腾记一:读指定文件夹,输出该文件夹的文件树详解-创新互联
前言

用来干什么:想干嘛干嘛
为什么写:写来玩,学习node.js文件系统相关api;树结构这种东西还是挺不错的,会用会造才是真的会
用了什么: fs.readdir(dir), fs.stat(dir).isFile(), path处理路径等
思路:
- 读取当前文件夹(不是文件夹的另作处理),获得其下所有文件和目录组成的数组;
- 循环该数组,判断是文件夹还是文件,文件的话直接push到childFiles(对象有两个属性:short文件名,full完整文件路径)
- 文件夹的话,先把当前文件夹作为key,存到父级文件夹的childDir属性下,然后自调用传当前文件夹路径
- 每一层文件夹都包含三个属性:dir文件夹路径,childFiles子文件,childDir子文件夹,存储为对象结构
- 以上步骤重复,直到达到最底层空文件夹或该文件夹只有文件
输出的样子components-dir-tree.json
{
"dir": "D:\\node-test\\components",
"childFiles": [
{
"short": "components-dir-tree.json",
"full": "D:\\node-test\\components\\components-dir-tree.json"
},
{
"short": "file.js",
"full": "D:\\node-test\\components\\file.js"
},
{
"short": "index.js",
"full": "D:\\node-test\\components\\index.js"
}
],
"childDir": {
"no": null,
"test": {
"dir": "D:\\node-test\\components\\test",
"childFiles": [],
"childDir": {
"aa": {
"dir": "D:\\node-test\\components\\test\\aa",
"childFiles": [
{
"short": "bb.js",
"full": "D:\\node-test\\components\\test\\aa\\bb.js"
}
],
"childDir": {
"cc": null
}
}
}
}
}
}
。 文章题目:Node.js折腾记一:读指定文件夹,输出该文件夹的文件树详解-创新互联
转载来于:http://www.jxjierui.cn/article/dhopce.html


咨询
建站咨询
