Skip to content

Commit

Permalink
feat(util): readJsonFileSync
Browse files Browse the repository at this point in the history
Co-authored-by: Mohammad Honarvar <[email protected]>
  • Loading branch information
alimd and mohammadhonarvar committed May 7, 2023
1 parent 73bb495 commit 659b2ea
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions core/util/src/node/_logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import {createLogger} from '@alwatr/logger';
export const logger = createLogger('alwatr/util');
42 changes: 42 additions & 0 deletions core/util/src/node/fs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {existsSync, readFileSync, writeFileSync, renameSync, mkdirSync} from 'node:fs';
import {rename, mkdir, writeFile, readFile} from 'node:fs/promises';
import {dirname} from 'node:path';

import {logger} from './_logger.js';

/**
* Enhanced read json file.
* @example
* const fileContent = readJsonFileSync('./file.json');
*/
export const readJsonFileSync = <T>(path: string): T | null => {
logger.logMethodArgs?.('readJsonFileSync', path);

if (!existsSync(path)) {
return null;
}

const timeKey = path.substring(path.lastIndexOf('/') + 1);
logger.time?.(`readJsonFileSync(${timeKey})`);

let fileContent: string;
try {
fileContent = readFileSync(path, {encoding: 'utf-8', flag: 'r'});
}
catch (err) {
logger.error('readJsonFileSync', 'read_file_failed', err);
throw new Error('read_file_failed');
}

let data;
try {
data = JSON.parse(fileContent) as T;
}
catch (err) {
logger.error('readJsonFileSync', 'invalid_json', err);
throw new Error('invalid_json');
}

console.timeEnd(`readJsonFileSync(${timeKey})`);
return data;
};
1 change: 1 addition & 0 deletions core/util/src/node/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './fs.js';

0 comments on commit 659b2ea

Please sign in to comment.