-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
52 lines (43 loc) · 1.48 KB
/
index.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import fs from 'fs/promises';
import { join } from 'path';
/**
* 类型:过滤类型 (filter type)
*/
type TFilterType = 'all' | 'file' | 'dir';
/**
* 获取目录下的所有文件或目录 (Get all files or directories under the directory)
* @param {string} dirPath 目录路径 (directory path)
* @param {boolean} [includeSubDirs = false] 是否包含子目录 (Whether to include subdirectories)
* @param {TFilterType} [filter = 'all'] 过滤类型 (filter type)
* @returns {Promise<string[]>} 文件或目录路径数组 (File or directory path array)
*/
const getDir = async (dirPath: string, includeSubDirs: boolean = false, filter: TFilterType = 'all'): Promise<string[]> => {
const results: string[] = [];
const stack: string[] = [dirPath];
while (stack.length > 0) {
const currentPath = stack.pop()!;
try {
const items = await fs.readdir(currentPath, { withFileTypes: true });
for (const item of items) {
const fullPath = join(currentPath, item.name);
if (item.isDirectory()) {
if (filter === 'dir' || filter === 'all') {
results.push(fullPath);
}
if (includeSubDirs) {
stack.push(fullPath);
}
} else if (item.isFile() && (filter === 'file' || filter === 'all')) {
results.push(fullPath);
}
}
} catch (err) {
if (err instanceof Error) {
throw err;
}
return [];
}
}
return results;
};
export default getDir;