前言
用来干什么:想干嘛干嘛
为什么写:写来玩,学习node.js文件系统相关api;树结构这种东西还是挺不错的,会用会造才是真的会
用了什么: fs.readdir(dir), fs.stat(dir).isFile(), path处理路径等
思路:
输出的样子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;
新闻热点
疑难解答
图片精选