3 import chalk from
'chalk';
5 import logger from
'./Logger';
6 import Utils from
'./Utils';
7 import type { EmptyObject
} from
'../types/EmptyObject';
8 import type { HandleErrorParams
} from
'../types/Error';
9 import type { FileType
} from
'../types/FileType';
10 import type { JsonType
} from
'../types/JsonType';
12 export default class FileUtils
{
13 private constructor() {
14 // This is intentional
17 public static watchJsonFile
<T
extends JsonType
>(
21 refreshedVariable
?: T
,
22 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
23 if (!Utils
.isEmptyString(filename
) && event
=== 'change') {
25 logger
.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
26 refreshedVariable
&& (refreshedVariable
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
28 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
34 ): fs
.FSWatcher
| undefined {
35 if (!Utils
.isEmptyString(file
)) {
37 return fs
.watch(file
, listener
);
39 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
44 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
48 public static handleFileException(
52 error
: NodeJS
.ErrnoException
,
53 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
55 const prefix
= !Utils
.isEmptyString(logPrefix
) ? `${logPrefix} ` : '';
59 logMsg
= `${fileType} file ${file} not found:`;
62 logMsg
= `${fileType} file ${file} already exists:`;
65 logMsg
= `${fileType} file ${file} access denied:`;
68 logMsg
= `${fileType} file ${file} error:`;
70 if (params
?.consoleOut
) {
71 logMsg
= `${logMsg} `;
72 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
);
74 logger
.warn(`${prefix}${logMsg}`, error
);
76 if (params
?.throwError
) {