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