国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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;            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 大兴区| 安顺市| 桃园市| 靖西县| 洛川县| 宁武县| 永济市| 沁源县| 阿尔山市| 镶黄旗| 梁河县| 喀什市| 鹤庆县| 鄄城县| 深水埗区| 南昌市| 潼南县| 开鲁县| 麦盖提县| 永胜县| 沙雅县| 微山县| 民丰县| 吉林市| 乐陵市| 泽州县| 镶黄旗| 墨竹工卡县| 新营市| 泾川县| 客服| 秀山| 宁远县| 兴城市| 余江县| 宝鸡市| 关岭| 沾益县| 大安市| 关岭| 武城县|