From 0c9528befb067bb8ad7e4b6ee148cd3b74a49a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Thu, 3 Aug 2023 23:06:35 +0200 Subject: [PATCH] Toolbox => Add some files functions --- helpers/Toolbox.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/helpers/Toolbox.ts b/helpers/Toolbox.ts index 1a51f23..55fde4d 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) + }; + } } -- GitLab