-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
74 lines (63 loc) · 1.87 KB
/
index.js
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
import { join } from "node:path";
export default async function getFolderSize(itemPath, options) {
return await core(itemPath, options, { errors: true });
}
getFolderSize.loose = async (itemPath, options) =>
await core(itemPath, options);
getFolderSize.strict = async (itemPath, options) =>
await core(itemPath, options, { strict: true });
async function core(rootItemPath, options = {}, returnType = {}) {
const fs = options.fs || (await import("node:fs/promises"));
let folderSize = 0n;
const foundInos = new Set();
const errors = [];
await processItem(rootItemPath);
async function processItem(itemPath) {
if (options.ignore?.test(itemPath)) return;
const stats = returnType.strict
? await fs.lstat(itemPath, { bigint: true })
: await fs
.lstat(itemPath, { bigint: true })
.catch((error) => errors.push(error));
if (typeof stats !== "object") return;
if (!foundInos.has(stats.ino)) {
foundInos.add(stats.ino);
folderSize += stats.size;
}
if (stats.isDirectory()) {
const directoryItems = returnType.strict
? await fs.readdir(itemPath)
: await fs
.readdir(itemPath)
.catch((error) => errors.push(error));
if (typeof directoryItems !== "object") return;
await Promise.all(
directoryItems.map((directoryItem) =>
processItem(join(itemPath, directoryItem)),
),
);
}
}
if (!options.bigint) {
if (folderSize > BigInt(Number.MAX_SAFE_INTEGER)) {
const error = new RangeError(
"The folder size is too large to return as a Number. You can instruct this package to return a BigInt instead.",
);
if (returnType.strict) {
throw error;
}
errors.push(error);
folderSize = Number.MAX_SAFE_INTEGER;
} else {
folderSize = Number(folderSize);
}
}
if (returnType.errors) {
return {
size: folderSize,
errors: errors.length > 0 ? errors : null,
};
} else {
return folderSize;
}
}