From 72a4ba79f279ea7ac6c6570fdcffa5a0bb6ca1e2 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Sat, 30 Nov 2019 18:34:21 +0100 Subject: [PATCH] Can generate random new file name --- src/utils/UserDataUtils.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/utils/UserDataUtils.ts b/src/utils/UserDataUtils.ts index c5a8a5f..eb503b8 100644 --- a/src/utils/UserDataUtils.ts +++ b/src/utils/UserDataUtils.ts @@ -1,6 +1,7 @@ import { conf } from "../helpers/ConfigHelper"; import { join } from "path"; import { existsSync, mkdirSync, writeFileSync } from "fs"; +import { randomStr } from "./CryptUtils"; /** * User data utilities @@ -52,4 +53,26 @@ export function prepareFileCreation(userID: number, folderName: string) : string } return subfolder; +} + +/** + * Generate a new file name in order to create a new file + * + * @param dir Target directory + * @param ext File extension + * @returns Generated file name (including dir) + */ +export function generateNewUserDataFileName(dir: string, ext: string) : string { + const sys_dir = pathUserData(dir, true); + + if(!existsSync(sys_dir)) + throw Error("Trying to create file into " + sys_dir + " but this directory does not exists!"); + + // Generate random file name + let filename : string; + do { + filename = randomStr(25) + "." + ext; + } while(existsSync(join(sys_dir, filename))); + + return join(dir, filename); } \ No newline at end of file