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