1 import { JsonType
, JsonValue
} from
'../types/JsonType';
3 import { EmptyObject
} from
'../types/EmptyObject';
4 import { FileType
} from
'../types/FileType';
5 import { HandleErrorParams
} from
'../types/Error';
6 import Utils from
'./Utils';
7 import chalk from
'chalk';
9 import logger from
'./Logger';
11 export default class FileUtils
{
12 static watchJsonFile
<T
extends JsonType
| JsonValue
>(
17 listener
: fs
.WatchListener
<string> = (event
, filename
) => {
18 if (filename
&& event
=== 'change') {
20 logger
.debug(logPrefix
+ ' ' + fileType
+ ' file ' + file
+ ' have changed, reload');
21 attribute
&& (attribute
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as T
);
23 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
32 fs
.watch(file
, listener
);
34 FileUtils
.handleFileException(logPrefix
, fileType
, file
, error
as NodeJS
.ErrnoException
, {
39 logger
.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
43 static handleFileException(
47 error
: NodeJS
.ErrnoException
,
48 params
: HandleErrorParams
<EmptyObject
> = { throwError
: true, consoleOut
: false }
50 const prefix
= !Utils
.isEmptyString(logPrefix
) ? logPrefix
+ ' ' : '';
51 if (error
.code
=== 'ENOENT') {
52 if (params
?.consoleOut
) {
54 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' not found: '),
58 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' not found: %j', error
);
60 } else if (error
.code
=== 'EEXIST') {
61 if (params
?.consoleOut
) {
63 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' already exists: '),
67 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' already exists: %j', error
);
69 } else if (error
.code
=== 'EACCES') {
70 if (params
?.consoleOut
) {
72 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' access denied: '),
76 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' access denied: %j', error
);
79 if (params
?.consoleOut
) {
81 chalk
.green(prefix
) + chalk
.yellow(fileType
+ ' file ' + file
+ ' error: '),
85 logger
.warn(prefix
+ fileType
+ ' file ' + file
+ ' error: %j', error
);
87 if (params
?.throwError
) {