使用tree生成目录树结构

前言

有时候想要展示一个项目的目录结构,对该项目进行文档描述性说明,用于解释其项目中各个目录以及文件代表的含义。在readme文档中逐行手写显然有些笨了。在Windows的Dos终端下有tree命令,不过其参数有限,无法过滤特定的文件;而且在Linux和git bash终端下,也无法直接使用。

apt 安装方式 (推荐)

1
sudo apt-get install tree

基于tree-node-cli

类似树的格式列出目录的内容,类似于Linux树命令。提供了CLI和Node API 安装:

1
npm install -g tree-node-cli
tree的命令使用帮助文档:终端下输入tree --help时,终端下就会输出tree命令使用的一些参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Usage: tree [options]

Options:
-V, --version output the version number
-a, --all-files All files, include hidden files, are printed.
--dirs-first List directories before files.
-d, --dirs-only List directories only.
-s, --sizes Print the size of each file in bytes along with the
name.
-I, --exclude [patterns] Exclude files that match the pattern. | separates
alternate patterns. Wrap your entire pattern in
double quotes. E.g. `"node_modules|coverage".
-L, --max-depth <n> Max display depth of the directory tree.
-r, --reverse Sort the output in reverse alphabetic order.
-F, --trailing-slash Append a '/' for directories.
-S, --line-ascii Turn on ASCII line graphics.
-h, --help display help for command
- tree -L n 显示项目的层级。n表示层级数。比如你想要显示项目的2层结构,可以用tree -l 2 - tree -I pattern 用于过滤不想要显示的文件或者文件夹。比如你想要过滤项目中的node_modules文件夹,可以使用tree -I "node_modules",如果想要过滤多个目录文件,也可以tree -I "node_modules|public|test_*",最后一个使用到正则匹配,这样以test_开头的文件夹都不会被显示出来,目录与目录之间用竖线隔开,中间不要有空格 - tree > tree.md 将项目结构输出到tree.md这个文件与在windows DOS的tree命令是一样的,但是在DOS终端下无法使用类似Linux下的一些参数,进行过滤操作

如果我们要显示某个项目下2层的所有文件结构,同时又过滤node_modules文件夹,可以这么写 tree -L 2 -I "要过滤的文件名",注意根据文档的参数,这是区分大小写的,而且要过滤的文件名必须得用双引号或者单引号包裹起来,在Linux命令行里,参数的大小写含义是有别的,上面文档的参数是什么,就应该是什么的,这点与windows是不一样的,Windows下的dos命令是不区分大小写的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$ tree -L 2 -I "node_modules"
Blog
├── _config.landscape.yml
├── _config.yml
├── db.json
├── package-lock.json
├── package.json
├── public
│ ├── 2021
│ ├── 2022
│ ├── about
│ ├── archives
│ ├── categories
│ ├── css
│ ├── images
│ ├── index.html
│ ├── js
│ ├── page
│ ├── search.xml
│ ├── shuoshuo
│ └── tags
├── scaffolds
│ ├── draft.md
│ ├── page.md
│ └── post.md
├── source
│ ├── _posts
│ ├── about
│ ├── categories
│ ├── shuoshuo
│ └── tags
└── themes
└── landscape

输出到tree.md,可以这么写:

1
tree -L 3 -I "node_modules" > tree.md

参考

https://juejin.cn/post/6844903861254094862


使用tree生成目录树结构
https://nessaj7.github.io/2022/05/11/88384542fd78.html
作者
kuhn
发布于
2022年5月11日
许可协议