Skip to content

Commit

Permalink
refactor(node-fs): readJson function
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jan 8, 2024
1 parent 28544c9 commit 086f6c6
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions packages/node-fs/src/read-json.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {logger} from './common';
import {parseJson} from './json';
import {readFile} from './read-file';
import {readFile, readFileSync} from './read-file';

import type {MaybePromise} from '@alwatr/type-helper';
import type {Dictionary, MaybePromise} from '@alwatr/type-helper';

/**
* Enhanced read json file (async).
Expand All @@ -14,7 +14,7 @@ import type {MaybePromise} from '@alwatr/type-helper';
* const fileContent = await readJson('./file.json');
* ```
*/
export function readJson(path: string): Promise<unknown>;
export function readJson<T extends Dictionary>(path: string): Promise<T>;
/**
* Enhanced read json file (sync).
*
Expand All @@ -26,7 +26,7 @@ export function readJson(path: string): Promise<unknown>;
* const fileContent = readJson('./file.json', true);
* ```
*/
export function readJson(path: string, sync: true): unknown;
export function readJson<T extends Dictionary>(path: string, sync: true): T;
/**
* Enhanced read json file.
*
Expand All @@ -38,7 +38,7 @@ export function readJson(path: string, sync: true): unknown;
* const fileContent = await readJson('./file.json', sync);
* ```
*/
export function readJson(path: string, sync: boolean): MaybePromise<unknown>;
export function readJson<T extends Dictionary>(path: string, sync: boolean): MaybePromise<T>;
/**
* Enhanced read json file.
*
Expand All @@ -50,11 +50,12 @@ export function readJson(path: string, sync: boolean): MaybePromise<unknown>;
* const fileContent = await readJson('./file.json');
* ```
*/
export function readJson(path: string, sync = false): MaybePromise<unknown> {
export function readJson<T extends Dictionary>(path: string, sync = false): MaybePromise<T> {
logger.logMethodArgs?.('readJson', {path: path.slice(-32), sync});
if (sync === true) {
return parseJson(readFile(path, true));
return parseJson<T>(readFileSync(path));
}
else {
return readFile(path).then((content) => parseJson<T>(content));
}
// else, async mode
return readFile(path).then((content) => parseJson(content));
}

0 comments on commit 086f6c6

Please sign in to comment.