-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnode.ts
104 lines (88 loc) · 2.19 KB
/
node.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { resolve } from "node:path";
import { runtime } from "std-env";
import prettyBytes from "pretty-bytes";
import { lstat, readdir } from "node:fs/promises";
interface Options {
/**
* @default false
*/
loose?: boolean;
}
async function strictGetFileSize(path: string) {
const { size } = await lstat(path);
return size;
}
async function looseGetFileSize(path: string) {
try {
const size = await strictGetFileSize(path);
return size;
} catch (error) {
return 0;
}
}
export async function getFolderSize(
base: string,
pretty?: false,
options?: Options,
): Promise<number>;
export async function getFolderSize(
base: string,
pretty?: true,
options?: Options,
): Promise<string>;
export async function getFolderSize(
base: string,
pretty = false,
options?: Options,
) {
const { loose = false } = options || {};
let total = 0;
const sumTotal = (size: number) => total += size;
const getFileSize = loose ? looseGetFileSize : strictGetFileSize;
// bun (use recursive)
if (runtime === "bun") {
const dirents = await readdir(base, {
recursive: true,
withFileTypes: true,
});
if (dirents.length === 0) {
return mayBeWithPrettyBytes();
}
const promises = dirents.map(async (dirent) => {
if (!dirent.isFile()) {
return;
}
const size = await getFileSize(resolve(base, dirent.name));
sumTotal(size);
});
await Promise.all(promises);
return mayBeWithPrettyBytes();
}
const dirents = await readdir(base, {
withFileTypes: true,
});
if (dirents.length === 0) {
return mayBeWithPrettyBytes();
}
const promises: Array<Promise<number>> = [];
for (const dirent of dirents) {
if (dirent.isFile()) {
const path = resolve(base, dirent.name);
promises.push(
getFileSize(path).then(sumTotal),
);
continue;
}
if (dirent.isDirectory()) {
const path = resolve(base, dirent.name);
promises.push(
getFolderSize(path, false, options).then(sumTotal),
);
}
}
await Promise.all(promises);
return mayBeWithPrettyBytes();
function mayBeWithPrettyBytes() {
return pretty ? prettyBytes(total) : total;
}
}