b057d7f7e844b4684f823903bc22a60f98e200dd
1 import { EmptyObject
} from
'../types/EmptyObject';
2 import { FileType
} from
'../types/FileType';
3 import { HandleErrorParams
} from
'../types/Error';
4 import { JsonType
} from
'../types/JsonType';
5 import Utils from
'./Utils';
6 import chalk from
'chalk';
8 import logger from
'./Logger';
10 export default class FileUtils
{
11 static watchJsonFile
<T
extends JsonType
>(
16 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
17 if (filename
&& event
=== 'change') {
19 logger
.debug(logPrefix
+ ' ' + fileType
+ ' file ' + file
+ ' have changed, reload');
20 attribute
&& (attribute
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
22 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
31 fs
.watch(file
, listener
);
33 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
38 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
42 static handleFileException(
46 error
: NodeJS
.ErrnoException
,
47 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
49 const prefix
= !Utils
.isEmptyString(logPrefix
) ? logPrefix
+ ' ' : '';
50 if (error
.code
=== 'ENOENT') {
51 if (params
?.consoleOut
) {
53 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' not found: '),
57 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' not found: %j', error
);
59 } else if (error
.code
=== 'EEXIST') {
60 if (params
?.consoleOut
) {
62 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' already exists: '),
66 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' already exists: %j', error
);
68 } else if (error
.code
=== 'EACCES') {
69 if (params
?.consoleOut
) {
71 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' access denied: '),
75 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' access denied: %j', error
);
78 if (params
?.consoleOut
) {
80 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' error: '),
84 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' error: %j', error
);
86 if (params
?.throwError
) {