Commit | Line | Data |
---|---|---|
130783a7 | 1 | import fs from 'node:fs'; |
8114d10e | 2 | |
51022aa0 | 3 | import { ErrorUtils } from './ErrorUtils'; |
878e026c JB |
4 | import { logger } from './Logger'; |
5 | import { Utils } from './Utils'; | |
51022aa0 | 6 | import type { FileType, JsonType } from '../types'; |
23132a44 | 7 | |
268a74bb | 8 | export class FileUtils { |
d5bd1c00 JB |
9 | private constructor() { |
10 | // This is intentional | |
11 | } | |
12 | ||
9d7484a4 | 13 | public static watchJsonFile<T extends JsonType>( |
a95873d8 | 14 | file: string, |
7164966d JB |
15 | fileType: FileType, |
16 | logPrefix: string, | |
9d7484a4 | 17 | refreshedVariable?: T, |
a95873d8 | 18 | listener: fs.WatchListener<string> = (event, filename) => { |
5a2a53cf | 19 | if (Utils.isNotEmptyString(filename) && event === 'change') { |
a95873d8 | 20 | try { |
cca3d474 | 21 | logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); |
9d7484a4 | 22 | refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); |
a95873d8 | 23 | } catch (error) { |
51022aa0 JB |
24 | ErrorUtils.handleFileException( |
25 | file, | |
26 | fileType, | |
27 | error as NodeJS.ErrnoException, | |
28 | logPrefix, | |
29 | { | |
30 | throwError: false, | |
31 | } | |
32 | ); | |
a95873d8 JB |
33 | } |
34 | } | |
35 | } | |
1895299d | 36 | ): fs.FSWatcher | undefined { |
5a2a53cf | 37 | if (Utils.isNotEmptyString(file)) { |
a95873d8 | 38 | try { |
9d7484a4 | 39 | return fs.watch(file, listener); |
a95873d8 | 40 | } catch (error) { |
51022aa0 | 41 | ErrorUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { |
a95873d8 JB |
42 | throwError: false, |
43 | }); | |
44 | } | |
45 | } else { | |
46 | logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); | |
47 | } | |
48 | } | |
23132a44 | 49 | } |