-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathfs.ts
96 lines (82 loc) · 2.35 KB
/
fs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {existsSync as fsExistsSync, Stats} from 'node:fs'
import {readFile, stat} from 'node:fs/promises'
import {isProd} from './util'
/**
* Parser for Args.directory and Flags.directory. Checks that the provided path
* exists and is a directory.
* @param input flag or arg input
* @returns Promise<string>
*/
export const dirExists = async (input: string): Promise<string> => {
let dirStat: Stats
try {
dirStat = await stat(input)
} catch {
throw new Error(`No directory found at ${input}`)
}
if (!dirStat.isDirectory()) {
throw new Error(`${input} exists but is not a directory`)
}
return input
}
/**
* Parser for Args.file and Flags.file. Checks that the provided path
* exists and is a file.
* @param input flag or arg input
* @returns Promise<string>
*/
export const fileExists = async (input: string): Promise<string> => {
let fileStat: Stats
try {
fileStat = await stat(input)
} catch {
throw new Error(`No file found at ${input}`)
}
if (!fileStat.isFile()) {
throw new Error(`${input} exists but is not a file`)
}
return input
}
class ProdOnlyCache extends Map<string, string> {
set(key: string, value: string): this {
if (isProd() ?? false) {
super.set(key, value)
}
return this
}
}
const cache = new ProdOnlyCache()
/**
* Read a file from disk and cache its contents if in production environment.
*
* Will throw an error if the file does not exist.
*
* @param path file path of JSON file
* @param useCache if false, ignore cache and read file from disk
* @returns <T>
*/
export async function readJson<T = unknown>(path: string, useCache = true): Promise<T> {
if (useCache && cache.has(path)) {
return JSON.parse(cache.get(path)!) as T
}
const contents = await readFile(path, 'utf8')
cache.set(path, contents)
return JSON.parse(contents) as T
}
/**
* Safely read a file from disk and cache its contents if in production environment.
*
* Will return undefined if the file does not exist.
*
* @param path file path of JSON file
* @param useCache if false, ignore cache and read file from disk
* @returns <T> or undefined
*/
export async function safeReadJson<T>(path: string, useCache = true): Promise<T | undefined> {
try {
return await readJson<T>(path, useCache)
} catch {}
}
export function existsSync(path: string): boolean {
return fsExistsSync(path)
}