| 1 | import { type FSWatcher, type WatchListener, readFileSync, watch } from 'node:fs'; |
| 2 | |
| 3 | import { handleFileException } from './ErrorUtils'; |
| 4 | import { logger } from './Logger'; |
| 5 | import { isNotEmptyString } from './Utils'; |
| 6 | import type { FileType, JsonType } from '../types'; |
| 7 | |
| 8 | export const watchJsonFile = <T extends JsonType>( |
| 9 | file: string, |
| 10 | fileType: FileType, |
| 11 | logPrefix: string, |
| 12 | refreshedVariable?: T, |
| 13 | listener: WatchListener<string> = (event, filename) => { |
| 14 | if (isNotEmptyString(filename) && event === 'change') { |
| 15 | try { |
| 16 | logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); |
| 17 | refreshedVariable && (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T); |
| 18 | } catch (error) { |
| 19 | handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { |
| 20 | throwError: false, |
| 21 | }); |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | ): FSWatcher | undefined => { |
| 26 | if (isNotEmptyString(file)) { |
| 27 | try { |
| 28 | return 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 | }; |