Commit | Line | Data |
---|---|---|
d972af76 | 1 | import { type FSWatcher, type WatchListener, readFileSync, watch } 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, | |
d972af76 | 13 | listener: WatchListener<string> = (event, filename) => { |
fa5995d6 | 14 | if (Utils.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 JB |
23 | } |
24 | } | |
d972af76 | 25 | ): FSWatcher | undefined => { |
fa5995d6 JB |
26 | if (Utils.isNotEmptyString(file)) { |
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 | }; |