# 文件操作
# 获取目录
// __dirname: 获得当前执行文件所在目录的完整目录名
// __filename: 获得当前执行文件的带有完整绝对路径的文件名
// process.cwd():获得当前执行node命令时候的文件夹目录名
// ./: 不使用require时候,./与process.cwd()一样,使用require时候,与__dirname一样
const path = require('path')
console.log('__dirname:', __dirname)
console.log('__filename:', __filename)
console.log('process.cwd():', process.cwd())
console.log('./:', path.resolve('./'))
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 获取文件结构树
const fs = require('fs');
const path = require('path');
const filePath = path.resolve('./');
/**
* 获取文件树
* @param {string} filePath 文件夹路径
* @param {string} rootPath 新生成path的根路径
* @param {Array<string>} ignoreDir 不需要处理的 文件/文件夹
* @param {number} deep 递归深度
*/
getDirTree(filePath, rootPath = '/', ignoreDir = ['.git', 'README.md', 'favourite', 'projectScript'], deep = 0) {
const fileArr = fs.readdirSync(filePath);
const fileResult = [];
fileArr.forEach(name => {
const stat = fs.statSync(path.resolve(filePath, name));
const isFile = stat.isFile(); // 是否为文件
// const isDir = stat.isDirectory(); // 是否为文件夹
if( ignoreDir.indexOf(name) > -1 ) return false; // 忽略文件
if(isFile && path.extname(name) !== '.md' ) return false; // 非md文件不处理
const pathStr = `${rootPath}${name}`;
let children = [];
if (!isFile) {
mdText = `${Array(3+deep).fill('#').join('')} ${name}`;
children = getMdDirTree(path.resolve(filePath, name), `${pathStr}/`, deep+1);
}
fileResult.push({
name,
path: pathStr,
type: isFile ? 'file' : 'dir',
mdText,
children
})
});
return fileResult;
}
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
35
36
37
38
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
35
36
37
38