X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2Fperformance-storage%2FJSONFileStorage.ts;h=60e544372f0650ffdedb6d4a7c7c34c61831d340;hb=8eac9a09368f841fc44e980f31674146833e449b;hp=4b5085cb1787f005e023b45e64bffe0a31c5db9c;hpb=9ef75e34cd01ecd7f75ce08ca7e4719d3c2b858b;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/performance-storage/JSONFileStorage.ts b/src/utils/performance-storage/JSONFileStorage.ts index 4b5085cb..60e54437 100644 --- a/src/utils/performance-storage/JSONFileStorage.ts +++ b/src/utils/performance-storage/JSONFileStorage.ts @@ -11,10 +11,29 @@ export class JSONFileStorage extends Storage { public storePerformanceStatistics(performanceStatistics: Statistics): void { const performanceJSONFilePath = path.join(path.resolve(__dirname, '../../../'), this.storageURI.pathname.replace(/(?:^\/)|(?:\/$)/g, '')); - fs.appendFile(performanceJSONFilePath, JSON.stringify(performanceStatistics, null, 2), 'utf8', (err) => { - if (err) { - FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, err); + if (!fs.existsSync(performanceJSONFilePath)) { + this.open(performanceJSONFilePath); + } + fs.readFile(performanceJSONFilePath, 'utf-8', (error, data) => { + if (error) { + FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, error); + } else { + const performanceRecords: Statistics[] = data ? JSON.parse(data.toString()) as Statistics[] : []; + performanceRecords.push(performanceStatistics); + fs.writeFile(performanceJSONFilePath, JSON.stringify(performanceRecords, null, 2), 'utf-8', (err) => { + if (err) { + FileUtils.handleFileException(this.logPrefix, 'Performance measurements', performanceJSONFilePath, err); + } + }); } }); } + + private open(filePath: string): void { + try { + fs.openSync(filePath, 'w+'); + } catch (error) { + FileUtils.handleFileException(this.logPrefix, 'Performance measurements', filePath, error); + } + } }