build: switch to NodeNext module resolution
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
CommitLineData
d972af76 1import { type FSWatcher, type WatchListener, readFileSync, watch } from 'node:fs';
8114d10e 2
a6ef1ece
JB
3import { handleFileException } from './ErrorUtils.js';
4import { logger } from './Logger.js';
5import { isNotEmptyString } from './Utils.js';
6import type { FileType, JsonType } from '../types/index.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 {
fa5995d6 16 logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
d972af76 17 refreshedVariable && (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T);
a95873d8 18 } catch (error) {
fa5995d6 19 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
a95873d8
JB
20 throwError: false,
21 });
22 }
a95873d8 23 }
5edd8ba0 24 },
d972af76 25): FSWatcher | undefined => {
9bf0ef23 26 if (isNotEmptyString(file)) {
fa5995d6 27 try {
d972af76 28 return watch(file, listener);
fa5995d6
JB
29 } catch (error) {
30 handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
31 throwError: false,
32 });
33 }
34 } else {
35 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
36 }
37};