X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FFileUtils.ts;h=ecb945bf40915841809270453428725cddf6b182;hb=d372f6da34cd27ce947ea2457dc37646a7edb472;hp=4e556a4bc1c3d642c8c9edecbb92049d5e880044;hpb=51022aa0d811eec79514fbeb56cb9556e7168cd7;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index 4e556a4b..ecb945bf 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -1,49 +1,37 @@ -import fs from 'node:fs'; +import { type FSWatcher, type WatchListener, readFileSync, watch } from 'node:fs'; -import { ErrorUtils } from './ErrorUtils'; +import { handleFileException } from './ErrorUtils'; import { logger } from './Logger'; -import { Utils } from './Utils'; +import { isNotEmptyString } from './Utils'; import type { FileType, JsonType } from '../types'; -export class FileUtils { - private constructor() { - // This is intentional - } - - public static watchJsonFile( - file: string, - fileType: FileType, - logPrefix: string, - refreshedVariable?: T, - listener: fs.WatchListener = (event, filename) => { - if (Utils.isNotEmptyString(filename) && event === 'change') { - try { - logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); - refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); - } catch (error) { - ErrorUtils.handleFileException( - file, - fileType, - error as NodeJS.ErrnoException, - logPrefix, - { - throwError: false, - } - ); - } - } - } - ): fs.FSWatcher | undefined { - if (Utils.isNotEmptyString(file)) { +export const watchJsonFile = ( + file: string, + fileType: FileType, + logPrefix: string, + refreshedVariable?: T, + listener: WatchListener = (event, filename) => { + if (isNotEmptyString(filename) && event === 'change') { try { - return fs.watch(file, listener); + logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); + refreshedVariable && (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T); } catch (error) { - ErrorUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { + handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { throwError: false, }); } - } else { - logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); } + }, +): FSWatcher | undefined => { + if (isNotEmptyString(file)) { + try { + return watch(file, listener); + } catch (error) { + handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { + throwError: false, + }); + } + } else { + logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); } -} +};