|
1
|
import { Dirent } from "fs" |
|
2
|
import { readdir } from "fs/promises" |
|
3
|
import { join } from "path" |
|
4
|
|
|
5
|
const MISSING_NODE_ERRORS = ["ENOTDIR", "ENOENT"] |
|
6
|
|
|
7
|
export async function readDir( |
|
8
|
dir: string, |
|
9
|
options?: { |
|
10
|
ignoreMissing?: boolean |
|
11
|
} |
|
12
|
) { |
|
13
|
try { |
|
14
|
const entries = await readdir(dir, { withFileTypes: true }) |
|
15
|
return entries |
|
16
|
} catch (error) { |
|
17
|
if (options?.ignoreMissing && MISSING_NODE_ERRORS.includes(error.code)) { |
|
18
|
return [] |
|
19
|
} |
|
20
|
throw error |
|
21
|
} |
|
22
|
} |
|
23
|
|
|
24
|
export async function readDirRecursive( |
|
25
|
dir: string, |
|
26
|
options?: { |
|
27
|
ignoreMissing?: boolean |
|
28
|
maxDepth?: number |
|
29
|
} |
|
30
|
): Promise<Dirent[]> { |
|
31
|
let allEntries: Dirent[] = [] |
|
32
|
const readRecursive = async (dir: string, depth: number = 1) => { |
|
33
|
const maxDepth = options?.maxDepth ?? Infinity |
|
34
|
try { |
|
35
|
const entries = await readdir(dir, { withFileTypes: true }) |
|
36
|
for (const entry of entries) { |
|
37
|
const fullPath = join(dir, entry.name) |
|
38
|
Object.defineProperty(entry, "path", { |
|
39
|
value: dir, |
|
40
|
}) |
|
41
|
allEntries.push(entry) |
|
42
|
|
|
43
|
if (entry.isDirectory() && depth < maxDepth) { |
|
44
|
await readRecursive(fullPath, depth + 1) |
|
45
|
} |
|
46
|
} |
|
47
|
} catch (error) { |
|
48
|
if (options?.ignoreMissing && error.code === "ENOENT") { |
|
49
|
return |
|
50
|
} |
|
51
|
|
|
52
|
throw error |
|
53
|
} |
|
54
|
} |
|
55
|
|
|
56
|
await readRecursive(dir) |
|
57
|
return allEntries |
|
58
|
} |