1 import fs from
'node:fs';
3 import chalk from
'chalk';
5 import { logger
} from
'./Logger';
6 import { Utils
} from
'./Utils';
7 import type { EmptyObject
, FileType
, HandleErrorParams
, JsonType
} from
'../types';
9 export class FileUtils
{
10 private constructor() {
11 // This is intentional
14 public static watchJsonFile
<T
extends JsonType
>(
18 refreshedVariable
?: T
,
19 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
20 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
22 logger
.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
23 refreshedVariable
&& (refreshedVariable
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
25 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
31 ): fs
.FSWatcher
| undefined {
32 if (Utils
.isNotEmptyString(file
)) {
34 return fs
.watch(file
, listener
);
36 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
41 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
45 public static handleFileException(
48 error
: NodeJS
.ErrnoException
,
50 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
52 const prefix
= Utils
.isNotEmptyString(logPrefix
) ? `${logPrefix} ` : '';
56 logMsg
= `${fileType} file ${file} not found:`;
59 logMsg
= `${fileType} file ${file} already exists:`;
62 logMsg
= `${fileType} file ${file} access denied:`;
65 logMsg
= `${fileType} file ${file} error:`;
67 if (params
?.consoleOut
) {
68 logMsg
= `${logMsg} `;
69 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
);
71 logger
.warn(`${prefix}${logMsg}`, error
);
73 if (params
?.throwError
) {