Node.js折腾记一:读指定文件夹,输出该文件夹的文件树详解

2020-06-17 05:56:40易采站长站整理

前言

用来干什么:想干嘛干嘛
为什么写:写来玩,学习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-testcomponents",
"childFiles": [
{
"short": "components-dir-tree.json",
"full": "D:node-testcomponentscomponents-dir-tree.json"
},
{
"short": "file.js",
"full": "D:node-testcomponentsfile.js"
},
{
"short": "index.js",
"full": "D:node-testcomponentsindex.js"
}
],
"childDir": {
"no": null,
"test": {
"dir": "D:node-testcomponentstest",
"childFiles": [],
"childDir": {
"aa": {
"dir": "D:node-testcomponentstestaa",
"childFiles": [
{
"short": "bb.js",
"full": "D:node-testcomponentstestaabb.js"
}
],
"childDir": {
"cc": null
}
}
}
}
}
}

目录结构(仅components)


|– components
    — index.js
    — file.js
    — components-dir-tree.json  // 生成的文件树对象的输出文件,方便查看
    — no
    — test
       — aa
        — cc

使用

将输出结果格式化写入到json文件,看起来一目了然


components/index.js:
/**
* init
*/
require('console-color-mr'); // 命令行样式
const fs = require('fs');
const path = require('path');
const { getDirTree, getDirName } = require('./file.js');

const componentDir = path.resolve(__dirname, './');
// console.log('componentDir: ', componentDir);