Skip to content

Commit

Permalink
feat(util): readJsonFile
Browse files Browse the repository at this point in the history
Co-authored-by: Mohammad Honarvar <honarvar.info@gmail.com>
  • Loading branch information
AliMD and mohammadhonarvar committed May 7, 2023
1 parent 659b2ea commit 940cba6
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions core/util/src/node/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,42 @@ export const readJsonFileSync = <T>(path: string): T | null => {
console.timeEnd(`readJsonFileSync(${timeKey})`);
return data;
};

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

if (!existsSync(path)) {
// existsSync is much faster than access.
return null;
}

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

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

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

console.timeEnd(`readJsonFile(${timeKey})`);
return data;
};

0 comments on commit 940cba6

Please sign in to comment.