-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathwalk-directory.ts
More file actions
60 lines (49 loc) · 1.43 KB
/
Copy pathwalk-directory.ts
File metadata and controls
60 lines (49 loc) · 1.43 KB
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
53
54
55
56
57
58
59
60
import { WalkerState } from "../../types";
import type { Dirent } from "fs";
export type WalkDirectoryFunction = (
state: WalkerState,
crawlPath: string,
directoryPath: string,
depth: number,
callback: (entries: Dirent[], directoryPath: string, depth: number) => void
) => void;
const readdirOpts = { withFileTypes: true } as const;
const walkAsync: WalkDirectoryFunction = (
state,
crawlPath,
directoryPath,
currentDepth,
callback
) => {
state.queue.enqueue();
if (currentDepth < 0) return state.queue.dequeue(null, state);
const { fs } = state;
state.visited.push(crawlPath);
// Perf: Node >= 10 introduced withFileTypes that helps us
// skip an extra fs.stat call.
fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync: WalkDirectoryFunction = (
state,
crawlPath,
directoryPath,
currentDepth,
callback
) => {
const { fs } = state;
if (currentDepth < 0) return;
state.visited.push(crawlPath);
let entries: Dirent[] = [];
try {
entries = fs.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback(entries, directoryPath, currentDepth);
};
export function build(isSynchronous: boolean): WalkDirectoryFunction {
return isSynchronous ? walkSync : walkAsync;
}