chore(deps-dev): apply updates
[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'
0749233f 4
66a7748d
JB
5import { handleFileException } from './ErrorUtils.js'
6import { logger } from './Logger.js'
7import { isNotEmptyString } from './Utils.js'
23132a44 8
fa5995d6
JB
9export const watchJsonFile = <T extends JsonType>(
10 file: string,
11 fileType: FileType,
12 logPrefix: string,
13 refreshedVariable?: T,
d972af76 14 listener: WatchListener<string> = (event, filename) => {
9bf0ef23 15 if (isNotEmptyString(filename) && event === 'change') {
a95873d8 16 try {
66a7748d
JB
17 logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`)
18 refreshedVariable != null &&
19 (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T)
a95873d8 20 } catch (error) {
fa5995d6 21 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
d1f5bfd8 22 throwError: false,
66a7748d 23 })
a95873d8 24 }
a95873d8 25 }
66a7748d 26 }
d972af76 27): FSWatcher | undefined => {
9bf0ef23 28 if (isNotEmptyString(file)) {
fa5995d6 29 try {
66a7748d 30 return watch(file, listener)
fa5995d6
JB
31 } catch (error) {
32 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
d1f5bfd8 33 throwError: false,
66a7748d 34 })
fa5995d6
JB
35 }
36 } else {
66a7748d 37 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`)
fa5995d6 38 }
66a7748d 39}