-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFolderSize.js
85 lines (75 loc) · 2.21 KB
/
FolderSize.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
75
76
77
78
79
80
81
82
83
84
85
import { resolve } from "path";
import fs from "fs/promises";
/**
* Recursively calculates the size of a folder.
* @param {string} path - The path to the folder.
* @returns {Promise<number>} - A Promise that resolves with the size of the folder in bytes.
*/
async function getFolderSize(path) {
let size = 0;
const dirs = await fs.readdir(path);
for (const dir of dirs) {
const currentPath = resolve(path, dir);
const stats = await fs.stat(currentPath);
if (stats.isDirectory()) {
size += await getFolderSize(currentPath);
} else {
size += stats.size;
}
}
return size;
}
/**
* Class for calculating and managing folder sizes.
*/
export default class FolderSize {
folders = [];
totalSize = 0; // Total size of all folders in bytes
/**
* Calculates the size of a folder.
* @param {string} path - The path to the folder.
* @returns {Promise<number>} - A Promise that resolves with the size of the folder in bytes.
*/
async getSize(path) {
const size = await getFolderSize(path);
return size;
}
/**
* Formats the folder size from bytes to MB.
* @param {number} size - The size of the folder in bytes.
* @returns {string} - The size of the folder in MB.
*/
formatSize(size) {
return `${(size / 1024 / 1024).toFixed(2)} MB`;
}
/**
* Stores the sizes of specified folders.
* @param {string[]} paths - The paths to the folders.
* @returns {Promise<void>} - A Promise that resolves once the sizes are calculated and stored.
*/
async storeFileSize(paths) {
for (const path of paths) {
const size = await getFolderSize(path);
this.folders.push({ path: path, size: size, isDeleted: false });
}
this.calculateTotalSize();
}
/**
* Calculates and sets the total size of all folders.
*/
calculateTotalSize() {
this.totalSize = this.folders.reduce(
(total, folder) => total + folder.size,
0,
);
}
/**
* Gets the total size of all deleted folders.
* @returns {number} - The size of the deleted folders in bytes.
*/
getDeletedSize() {
return this.folders.reduce((deletedSize, folder) => {
return folder.isDeleted ? deletedSize + folder.size : deletedSize;
}, 0);
}
}