From 230f4157a19ea539f6c245ef77e02512b7c9c91a Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Sun, 7 May 2023 22:07:41 +0330 Subject: [PATCH] feat(util): writeJsonFileSync Co-authored-by: Mohammad Honarvar --- core/util/src/node/fs.ts | 49 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/core/util/src/node/fs.ts b/core/util/src/node/fs.ts index 6d9dbefb5..4720f060a 100644 --- a/core/util/src/node/fs.ts +++ b/core/util/src/node/fs.ts @@ -79,3 +79,52 @@ export const readJsonFile = async (path: string): Promise => { return data; }; +/** + * Enhanced write json file. + * @example + * writeJsonFileSync('./file.json', { a:1, b:2, c:3 }); + */ +export const writeJsonFileSync = (path: string, data: unknown, space?: string | number): void => { + logger.logMethodArgs?.('writeJsonFileSync', path); + + const timeKey = path.substring(path.lastIndexOf('/') + 1); + logger.time?.(`writeJsonFileSync(${timeKey})`); + + let jsonContent; + try { + jsonContent = JSON.stringify(data, null, space); + } + catch (err) { + logger.error('writeJsonFileSync', 'stringify_failed', err); + throw new Error('stringify_failed'); + } + + if (existsSync(path)) { + try { + renameSync(path, path + '.bk'); + } + catch (err) { + logger.error('writeJsonFileSync', 'rename_failed', err); + } + } + else { + try { + mkdirSync(dirname(path), {recursive: true}); + } + catch (err) { + logger.error('writeJsonFileSync', 'make_dir_failed', err); + throw new Error('make_dir_failed'); + } + } + + try { + writeFileSync(path, jsonContent, {encoding: 'utf-8', flag: 'w'}); + } + catch (err) { + logger.error('writeJsonFileSync', 'write_file_failed', err); + throw new Error('write_file_failed'); + } + + logger.timeEnd?.(`writeJsonFileSync(${timeKey})`); +}; +