1 import fs from
'node:fs';
3 import chalk from
'chalk';
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';
10 export class FileUtils
{
11 private constructor() {
12 // This is intentional
15 public static watchJsonFile
<T
extends JsonType
>(
19 refreshedVariable
?: T
,
20 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
21 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
23 logger
.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
24 refreshedVariable
&& (refreshedVariable
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
26 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
32 ): fs
.FSWatcher
| undefined {
33 if (Utils
.isNotEmptyString(file
)) {
35 return fs
.watch(file
, listener
);
37 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
42 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
46 public static handleFileException(
49 error
: NodeJS
.ErrnoException
,
51 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
53 const prefix
= Utils
.isNotEmptyString(logPrefix
) ? `${logPrefix} ` : '';
57 logMsg
= `${fileType} file ${file} not found:`;
60 logMsg
= `${fileType} file ${file} already exists:`;
63 logMsg
= `${fileType} file ${file} access denied:`;
66 logMsg
= `${fileType} file ${file} error:`;
68 if (params
?.consoleOut
) {
69 logMsg
= `${logMsg} `;
70 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
);
72 logger
.warn(`${prefix}${logMsg}`, error
);
74 if (params
?.throwError
) {