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