1
- import { Stats , existsSync as fsExistsSync , readFileSync } from 'node:fs'
1
+ import { Stats , existsSync as fsExistsSync } from 'node:fs'
2
2
import { readFile , stat } from 'node:fs/promises'
3
3
4
4
import { isProd } from './util'
@@ -57,8 +57,17 @@ class ProdOnlyCache extends Map<string, string> {
57
57
58
58
const cache = new ProdOnlyCache ( )
59
59
60
- export async function readJson < T = unknown > ( path : string ) : Promise < T > {
61
- if ( cache . has ( path ) ) {
60
+ /**
61
+ * Read a file from disk and cache its contents if in production environment.
62
+ *
63
+ * Will throw an error if the file does not exist.
64
+ *
65
+ * @param path file path of JSON file
66
+ * @param useCache if false, ignore cache and read file from disk
67
+ * @returns <T>
68
+ */
69
+ export async function readJson < T = unknown > ( path : string , useCache = true ) : Promise < T > {
70
+ if ( useCache && cache . has ( path ) ) {
62
71
return JSON . parse ( cache . get ( path ) ! ) as T
63
72
}
64
73
@@ -67,25 +76,18 @@ export async function readJson<T = unknown>(path: string): Promise<T> {
67
76
return JSON . parse ( contents ) as T
68
77
}
69
78
70
- export function readJsonSync ( path : string , parse : false ) : string
71
- export function readJsonSync < T = unknown > ( path : string , parse ?: true ) : T
72
- export function readJsonSync < T = unknown > ( path : string , parse = true ) : T | string {
73
- if ( cache . has ( path ) ) {
74
- return JSON . parse ( cache . get ( path ) ! ) as T
75
- }
76
-
77
- const contents = readFileSync ( path , 'utf8' )
78
- cache . set ( path , contents )
79
- return parse ? ( JSON . parse ( contents ) as T ) : contents
80
- }
81
-
82
- export async function safeReadJson < T > ( path : string ) : Promise < T | undefined > {
83
- if ( cache . has ( path ) ) {
84
- return JSON . parse ( cache . get ( path ) ! ) as T
85
- }
86
-
79
+ /**
80
+ * Safely read a file from disk and cache its contents if in production environment.
81
+ *
82
+ * Will return undefined if the file does not exist.
83
+ *
84
+ * @param path file path of JSON file
85
+ * @param useCache if false, ignore cache and read file from disk
86
+ * @returns <T> or undefined
87
+ */
88
+ export async function safeReadJson < T > ( path : string , useCache = true ) : Promise < T | undefined > {
87
89
try {
88
- return await readJson < T > ( path )
90
+ return await readJson < T > ( path , useCache )
89
91
} catch { }
90
92
}
91
93
0 commit comments