首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:40:22
字体:
来源:转载
供稿:网友

前言

用来干什么:想干嘛干嘛
为什么写:写来玩,学习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          }        }      }    }  }}。

目录结构(仅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);const ComponentInit = (function init() { console.log('______ init ______'.blueBG, '/n'); let treeObj = getDirTree(componentDir); // console.log('treeObj: ',treeObj); if (treeObj) {  let outdir = `${__dirname}//${getDirName(componentDir)}-dir-tree.json`;  // 写入文件  fs.writeFile(outdir, JSON.stringify(treeObj, '', '/t'), 'utf8', (err) => {   if (err) throw err;   console.log(`目录树已输出为文件保存: ${outdir}`.greenBG);  }); } return init;})();module.exports = ComponentInit;            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选