JavaScript實現(xiàn)封裝一個快速生成目錄樹的全局腳本
說在前面
我們在很多地方都可以看到有這樣的目錄樹結(jié)構(gòu),目錄樹可以很好的介紹項目中各文件目錄的用途,幫助讀者了解整個項目結(jié)構(gòu)。由于自己在項目中需要用到這個目錄樹來進(jìn)行項目結(jié)構(gòu)介紹,但是在網(wǎng)上簡單的找了一下,沒找到自己想要的工具,于是就自己動手?jǐn)]了一個。
思路分析
首先我們需要先明確一下我們這個工具需要實現(xiàn)的功能:
- 1、可以生成指定目錄的文件樹文件
- 2、可以方便地在任意目錄下生成
那么我們需要做的也就是以下兩步:
- 1、編寫一個可以生成指定目錄文件樹的文件
- 2、將腳本封裝成全局腳本
為了方便插件的使用、提高用戶體驗,我們可以使用命令行交互的方式來獲取所需參數(shù)。
功能實現(xiàn)
一、使用命令行交互來獲取所需參數(shù)
編寫腳本之前我們需要先明確一下需要的參數(shù)
- 1、需要生成文件樹的根目錄路徑;
- 2、生成過程中需要忽略的文件或目錄;
- 3、生成文件樹的深度;
- 4、生成的文件樹文件存放路徑;
這里使用到了我自己之前基于inquirer
進(jìn)行二次封裝的@jyeontu/j-inquirer
,與inquirer
相比,@jyeontu/j-inquirer
增加了文件夾選擇器的交互方式,我們可以直接使用其來選擇需要生產(chǎn)目錄樹的文件目錄和生成文件存放的位置。
@jyeontu/j-inquirer
這個工具的具體使用手冊可以看這里:https://gitee.com/zheng_yongtao/node-scripting-tool/tree/master/src/JInquirer
const JInquirer = require("@jyeontu/j-inquirer"); const fs = require("fs"); const path = require("path"); async init() { const options = this.getOptions(); let j = new JInquirer(options); let res = await j.prompt(); this.config = res; this.generateTree(res); } getOptions() { const basePath = this.config.basePath || __dirname; return [ { type: "folder", message: "請選擇文件夾:", name: "basepath", default: "", pathType: "absolute", dirname: basePath, }, { type: "input", message: "請輸入需要過濾的文件名(英文逗號隔開):", name: "filterFile", notNull: false, }, { type: "input", message: "請輸入需要遍歷的層數(shù):", name: "stopFloor", notNull: false, }, { type: "folder", message: "請選擇生成文件存放位置:", name: "generatePath", default: "", pathType: "absolute", dirname: basePath, }, ]; }
獲取到我們需要的參數(shù)之后我們便可以開始編寫生成文件目錄樹的代碼了:
二、編寫目錄文件樹生成邏輯
1、遞歸獲取文件目錄
遞歸結(jié)束條件為傳入?yún)?shù)的最大遍歷深度:if (floor > stopFloor) return;
。
通過readdirSync
可以獲取指定目錄下的所有文件列表,通過statSync
方法獲取文件屬性,再通過isFile
方法判斷是文件還是目錄,如果當(dāng)前遍歷到的為目錄,則需要遞歸遍歷該目錄下的所有文件……
processDir(dirPath, dirTree = [], floor = 1) { const { stopFloor } = this.config; if (floor > stopFloor) return; let list = fs.readdirSync(dirPath); list = list.filter((item) => { return !this.isFilterPath(item); }); list.forEach((itemPath) => { const fullPath = path.join(dirPath, itemPath); const fileStat = fs.statSync(fullPath); const isFile = fileStat.isFile(); const dir = { name: itemPath, }; if (!isFile) { dir.children = this.processDir(fullPath, [], floor + 1); } dirTree.push(dir); }); return dirTree; }
2、過濾不需要的文件
有時候我們不希望打印出某些文件目錄(如:node_modules),我們在輸入配置的時候可以進(jìn)行設(shè)置,遍歷文件目錄的過程中會過濾掉相關(guān)的文件。
isFilterPath(item) { let { filterFile } = this.config; filterFile = filterFile.split(","); for (let i = 0; i < filterFile.length; i++) { let reg = filterFile[i]; if (item.match(reg) && item.match(reg)[0] === item) return true; } return false; }
3、將文件樹列表轉(zhuǎn)換為字符串
前面我們生成的文件樹是以列表的形式保存,現(xiàn)在我們需要將其轉(zhuǎn)換成使用制表符連接的字符串的格式。
consoleTree(tree, floor = 1, str = "", adder = "───", isLast = false) { str += adder; for (let i = 0; i < tree.length; i++) { if (floor === 1 && i === 0) { this.fileTree += "\n" + "┌" + str + tree[i].name; } else if ( (isLast || floor === 1) && i === tree.length - 1 && !tree[i].children ) { this.fileTree += "\n" + "└" + str + tree[i].name; } else { this.fileTree += "\n" + "├" + str + tree[i].name; } if (tree[i].children) this.consoleTree( tree[i].children, floor + 1, str, adder, (isLast || floor === 1) && i === tree.length - 1 ); } }
4、將生成的目錄樹寫入 txt 文件
前面我們已經(jīng)生成了字符串格式的目錄樹,所以我們可以直接將生成的字符串寫入 txt 文件即可,注意寫入前我們需要先將原有內(nèi)容情況。
writeTree(filePath, content) { this.clearTxt(filePath); fs.writeFileSync(filePath, `${content}`); } clearTxt(filePath) { this.fileTree = ""; fs.writeFileSync(filePath, ""); }
三、封裝成全局插件
1、準(zhǔn)備一個腳本文件
創(chuàng)建一個文件 bin.js 作為啟動腳本。
#!/usr/bin/env node const path = require("path"); const GetFileTree = require("./GetFileTree.js"); const basePath = process.argv[2] || path.join(process.argv[1], "../"); console.log(process.argv, basePath); const gft = new GetFileTree({ basePath }); gft.init();
2、package.json 中配置啟動命令
在package.json
文件中配置腳本啟動命令,需要設(shè)置 bin 屬性,這個配置幫助我們將包內(nèi)的可執(zhí)行腳本文件注入系統(tǒng)環(huán)境。多個命令時,支持對象配置命令:
{ "name": "mt-cli", "version": "1.0.1", "bin": { "getFileTree": "./bin.js" } }
3、上傳到 npm
登錄自己的 npm 賬號后可以使用命令將該包上傳到 npm 倉庫。
npm publish
四、插件安裝使用
1、插件安裝
npm i -g getFileTree
2、插件使用
全局安裝后我們就可以在任意目錄下使用getFileTree 目錄絕對路徑
命令來生成文件目錄樹,如下:
getFileTree E:\myGitee\md文件夾
然后按照提示選擇或輸入相關(guān)的參數(shù)即可,生成的文件如下:
源碼地址
https://gitee.com/zheng_yongtao/node-scripting-tool/tree/master/src/getFileTree
到此這篇關(guān)于JavaScript實現(xiàn)封裝一個快速生成目錄樹的全局腳本的文章就介紹到這了,更多相關(guān)JavaScript目錄樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!