refactor: cleanup eslint configuration
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
1 import { type FSWatcher, readFileSync, watch, type WatchListener } from 'node:fs'
2
3 import type { FileType, JsonType } from '../types/index.js'
4 import { handleFileException } from './ErrorUtils.js'
5 import { logger } from './Logger.js'
6 import { isNotEmptyString } from './Utils.js'
7
8 export const watchJsonFile = <T extends JsonType>(
9 file: string,
10 fileType: FileType,
11 logPrefix: string,
12 refreshedVariable?: T,
13 listener: WatchListener<string> = (event, filename) => {
14 if (isNotEmptyString(filename) && event === 'change') {
15 try {
16 logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`)
17 refreshedVariable != null &&
18 (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T)
19 } catch (error) {
20 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
21 throwError: false
22 })
23 }
24 }
25 }
26 ): FSWatcher | undefined => {
27 if (isNotEmptyString(file)) {
28 try {
29 return watch(file, listener)
30 } catch (error) {
31 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
32 throwError: false
33 })
34 }
35 } else {
36 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`)
37 }
38 }