![7ed8e7c446dc0cb86b2eb0e3932cc4dc.png](https://img-blog.csdnimg.cn/img_convert/7ed8e7c446dc0cb86b2eb0e3932cc4dc.png)
有时候需要做一些技术分享,对项目目录结构做一个简单的介绍,需要输出一个文本格式的项目目录结构。起初在github上面找了几个项目来做这个事,但是觉得使用很麻烦索性自己动手写一个,按照npm list 的输出方式输出20来行代码搞定使用方便。
代码
const fs = require("fs");
const path = require("path");
const rootDir = path.resolve(__dirname);
const createDirTree = (dir,skip) => {
console.log('+—— root');
const recur = (curDir) => {
fs.readdirSync(curDir,{withFileTypes:true}).forEach((value) => {
if(skip.includes(value.name)) return ;
const childPath = path.join(curDir,value.name);
const depths = childPath.replace(rootDir,'').split(path.sep).filter(Boolean).length ;
const isDirectory = value.isDirectory();
const prefix = `${'| '.repeat(depths -1)}${ isDirectory ? '+' : '`' }-- `;
console.log(`${prefix}${value.name}`);
if(isDirectory){
recur(path.join(curDir,value.name));
}
});
}
recur(dir);
}
createDirTree(rootDir,["node_modules",".vscode",".git",".next","_next"])
使用
copy上面代码放到自己想要输出目录结构的项目创建一个js文件用node去执行。
输出例子
+—— root
`-- .gitignore
`-- README.md
+-- components
| +-- Footer
| | `-- index.tsx
| +-- Header
| | `-- index.tsx
| +-- Loyout
| | `-- index.tsx
| +-- styles
+-- mock
| `-- quotes.json
`-- next-env.d.ts
`-- next.config.js
+-- out
| +-- 404
| | `-- index.html
| `-- 404.html
`-- package.json
+-- pages
| +-- P
| | `-- [id].tsx
| `-- about.tsx
| +-- api
| | `-- randomQuote.ts
| `-- index.tsx
| `-- post.tsx
+-- public
+-- styles
| `-- index.less
| `-- reset.less
`-- test.js
`-- tsconfig.json
`-- yarn.lock
github地址: JSlife23/DirTree