| 1 | import fs from 'node:fs'; |
| 2 | |
| 3 | import chalk from 'chalk'; |
| 4 | |
| 5 | // import { Utils, logger } from './internal'; |
| 6 | import { logger } from './Logger'; |
| 7 | import { Utils } from './Utils'; |
| 8 | import type { EmptyObject, FileType, HandleErrorParams, JsonType } from '../types'; |
| 9 | |
| 10 | export class FileUtils { |
| 11 | private constructor() { |
| 12 | // This is intentional |
| 13 | } |
| 14 | |
| 15 | public static watchJsonFile<T extends JsonType>( |
| 16 | file: string, |
| 17 | fileType: FileType, |
| 18 | logPrefix: string, |
| 19 | refreshedVariable?: T, |
| 20 | listener: fs.WatchListener<string> = (event, filename) => { |
| 21 | if (Utils.isNotEmptyString(filename) && event === 'change') { |
| 22 | try { |
| 23 | logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); |
| 24 | refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); |
| 25 | } catch (error) { |
| 26 | FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { |
| 27 | throwError: false, |
| 28 | }); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | ): fs.FSWatcher | undefined { |
| 33 | if (Utils.isNotEmptyString(file)) { |
| 34 | try { |
| 35 | return fs.watch(file, listener); |
| 36 | } catch (error) { |
| 37 | FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { |
| 38 | throwError: false, |
| 39 | }); |
| 40 | } |
| 41 | } else { |
| 42 | logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public static handleFileException( |
| 47 | file: string, |
| 48 | fileType: FileType, |
| 49 | error: NodeJS.ErrnoException, |
| 50 | logPrefix: string, |
| 51 | params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false } |
| 52 | ): void { |
| 53 | const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; |
| 54 | let logMsg: string; |
| 55 | switch (error.code) { |
| 56 | case 'ENOENT': |
| 57 | logMsg = `${fileType} file ${file} not found:`; |
| 58 | break; |
| 59 | case 'EEXIST': |
| 60 | logMsg = `${fileType} file ${file} already exists:`; |
| 61 | break; |
| 62 | case 'EACCES': |
| 63 | logMsg = `${fileType} file ${file} access denied:`; |
| 64 | break; |
| 65 | default: |
| 66 | logMsg = `${fileType} file ${file} error:`; |
| 67 | } |
| 68 | if (params?.consoleOut) { |
| 69 | logMsg = `${logMsg} `; |
| 70 | console.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error); |
| 71 | } else { |
| 72 | logger.warn(`${prefix}${logMsg}`, error); |
| 73 | } |
| 74 | if (params?.throwError) { |
| 75 | throw error; |
| 76 | } |
| 77 | } |
| 78 | } |