Commit | Line | Data |
---|---|---|
130783a7 | 1 | import fs from 'node:fs'; |
8114d10e | 2 | |
fa5995d6 | 3 | import { handleFileException } from './ErrorUtils'; |
878e026c JB |
4 | import { logger } from './Logger'; |
5 | import { Utils } from './Utils'; | |
51022aa0 | 6 | import type { FileType, JsonType } from '../types'; |
23132a44 | 7 | |
fa5995d6 JB |
8 | export const watchJsonFile = <T extends JsonType>( |
9 | file: string, | |
10 | fileType: FileType, | |
11 | logPrefix: string, | |
12 | refreshedVariable?: T, | |
13 | listener: fs.WatchListener<string> = (event, filename) => { | |
14 | if (Utils.isNotEmptyString(filename) && event === 'change') { | |
a95873d8 | 15 | try { |
fa5995d6 JB |
16 | logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); |
17 | refreshedVariable && (refreshedVariable = JSON.parse(fs.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 JB |
23 | } |
24 | } | |
fa5995d6 JB |
25 | ): fs.FSWatcher | undefined => { |
26 | if (Utils.isNotEmptyString(file)) { | |
27 | try { | |
28 | return fs.watch(file, listener); | |
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 | }; |