X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FFileUtils.ts;h=bc8dd07c24725d990ae282056fc5ab8d4243b942;hb=17ba3be0bb5c0bcb7fff2cefa877af975c0d043a;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..bc8dd07c 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -1,49 +1,38 @@ -import fs from 'node:fs'; +import { type FSWatcher, type WatchListener, readFileSync, watch } from 'node:fs' -import { ErrorUtils } from './ErrorUtils'; -import { logger } from './Logger'; -import { Utils } from './Utils'; -import type { FileType, JsonType } from '../types'; +import { handleFileException } from './ErrorUtils.js' +import { logger } from './Logger.js' +import { isNotEmptyString } from './Utils.js' +import type { FileType, JsonType } from '../types/index.js' -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 != null && + (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T) } catch (error) { - ErrorUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { - throwError: false, - }); + 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`) + } }