1 import fs from
'node:fs';
3 import chalk from
'chalk';
5 import { Utils
, logger
} from
'./internal';
6 import type { EmptyObject
, FileType
, HandleErrorParams
, JsonType
} from
'../types';
8 export class FileUtils
{
9 private constructor() {
10 // This is intentional
13 public static watchJsonFile
<T
extends JsonType
>(
17 refreshedVariable
?: T
,
18 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
19 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
21 logger
.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
22 refreshedVariable
&& (refreshedVariable
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
24 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
30 ): fs
.FSWatcher
| undefined {
31 if (Utils
.isNotEmptyString(file
)) {
33 return fs
.watch(file
, listener
);
35 FileUtils
.handleFileException(file
, fileType
, error
as NodeJS
.ErrnoException
, logPrefix
, {
40 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
44 public static handleFileException(
47 error
: NodeJS
.ErrnoException
,
49 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
51 const prefix
= Utils
.isNotEmptyString(logPrefix
) ? `${logPrefix} ` : '';
55 logMsg
= `${fileType} file ${file} not found:`;
58 logMsg
= `${fileType} file ${file} already exists:`;
61 logMsg
= `${fileType} file ${file} access denied:`;
64 logMsg
= `${fileType} file ${file} error:`;
66 if (params
?.consoleOut
) {
67 logMsg
= `${logMsg} `;
68 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
);
70 logger
.warn(`${prefix}${logMsg}`, error
);
72 if (params
?.throwError
) {