Reduce charging station instance memory footprint
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
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';
7 import fs from 'fs';
8 import logger from './Logger';
9
10 export default class FileUtils {
11 static watchJsonFile<T extends JsonType>(
12 logPrefix: string,
13 fileType: FileType,
14 file: string,
15 attribute?: T,
16 listener: fs.WatchListener<string> = (event, filename) => {
17 if (filename && event === 'change') {
18 try {
19 logger.debug(logPrefix + ' ' + fileType + ' file ' + file + ' have changed, reload');
20 attribute && (attribute = JSON.parse(fs.readFileSync(file, 'utf8')) as T);
21 } catch (error) {
22 FileUtils.handleFileException(logPrefix, fileType, file, error as NodeJS.ErrnoException, {
23 throwError: false,
24 });
25 }
26 }
27 }
28 ) {
29 if (file) {
30 try {
31 fs.watch(file, listener);
32 } catch (error) {
33 FileUtils.handleFileException(logPrefix, fileType, file, error as NodeJS.ErrnoException, {
34 throwError: false,
35 });
36 }
37 } else {
38 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
39 }
40 }
41
42 static handleFileException(
43 logPrefix: string,
44 fileType: FileType,
45 file: string,
46 error: NodeJS.ErrnoException,
47 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
48 ): void {
49 const prefix = !Utils.isEmptyString(logPrefix) ? logPrefix + ' ' : '';
50 if (error.code === 'ENOENT') {
51 if (params?.consoleOut) {
52 console.warn(
53 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' not found: '),
54 error
55 );
56 } else {
57 logger.warn(prefix + fileType + ' file ' + file + ' not found: %j', error);
58 }
59 } else if (error.code === 'EEXIST') {
60 if (params?.consoleOut) {
61 console.warn(
62 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' already exists: '),
63 error
64 );
65 } else {
66 logger.warn(prefix + fileType + ' file ' + file + ' already exists: %j', error);
67 }
68 } else if (error.code === 'EACCES') {
69 if (params?.consoleOut) {
70 console.warn(
71 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' access denied: '),
72 error
73 );
74 } else {
75 logger.warn(prefix + fileType + ' file ' + file + ' access denied: %j', error);
76 }
77 } else {
78 if (params?.consoleOut) {
79 console.warn(
80 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' error: '),
81 error
82 );
83 } else {
84 logger.warn(prefix + fileType + ' file ' + file + ' error: %j', error);
85 }
86 if (params?.throwError) {
87 throw error;
88 }
89 }
90 }
91 }