diff --git a/helpers/Toolbox.ts b/helpers/Toolbox.ts index 1a51f2303a3a647fe309810b0b0ff0e1247473c4..55fde4d28d156b4427731ee22971b3e8a4dd941b 100644 --- a/helpers/Toolbox.ts +++ b/helpers/Toolbox.ts @@ -1,7 +1,47 @@ +import fs from 'fs/promises'; +import path from 'path'; + + class Toolbox { public urlToPath(url: string): string { return url.replace(/^([a-z]{3,5}:\/{2})?[a-z.@]+(:[0-9]{1,5})?.(.*)/, '$3').replace('.git', ''); } + + /* + Source of getAllFiles and getTotalSize (modified for this project): https://coderrocketfuel.com/article/get-the-total-size-of-all-files-in-a-directory-using-node-js + */ + private async getAllFiles(dirPath: string, arrayOfFiles: Array<string> = []): Promise<Array<string>> { + let files = await fs.readdir(dirPath); + + await Promise.all(files.map(async file => { + if ( (await fs.stat(dirPath + '/' + file)).isDirectory() ) { + arrayOfFiles = await this.getAllFiles(dirPath + '/' + file, arrayOfFiles); + } else { + arrayOfFiles.push(path.join(dirPath, file)); + } + })); + + return arrayOfFiles; + }; + + private async getTotalSize(directoryPath: string): Promise<number> { + const arrayOfFiles = await this.getAllFiles(directoryPath); + + let totalSize = 0; + + for ( const filePath of arrayOfFiles ) { + totalSize += (await fs.stat(filePath)).size; + } + + return totalSize; + }; + + get fs() { + return { + getAllFiles : this.getAllFiles.bind(this), + getTotalSize: this.getTotalSize.bind(this) + }; + } }