(path: string, opts: readJSONOpts = {})
| 33 | |
| 34 | type readJSONOpts = { defaultVal?: Record<string, any>; isRoot?: boolean; isList?: boolean }; |
| 35 | export const readJSON = async (path: string, opts: readJSONOpts = {}) => { |
| 36 | const { defaultVal = {}, isRoot = false, isList = false } = opts; |
| 37 | const root = await chatRoot(); |
| 38 | let file = path; |
| 39 | |
| 40 | if (!isRoot) { |
| 41 | file = await join(root, path); |
| 42 | } |
| 43 | |
| 44 | if (!(await exists(file))) { |
| 45 | if ((await dirname(file)) !== root) { |
| 46 | await createDir(await dirname(file), { recursive: true }); |
| 47 | } |
| 48 | await writeTextFile( |
| 49 | file, |
| 50 | isList |
| 51 | ? '[]' |
| 52 | : JSON.stringify( |
| 53 | { |
| 54 | name: 'ChatGPT', |
| 55 | link: 'https://github.com/lencx/ChatGPT', |
| 56 | ...defaultVal, |
| 57 | }, |
| 58 | null, |
| 59 | 2, |
| 60 | ), |
| 61 | ); |
| 62 | } |
| 63 | |
| 64 | try { |
| 65 | return JSON.parse(await readTextFile(file)); |
| 66 | } catch (e) { |
| 67 | return {}; |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | type writeJSONOpts = { dir?: string; isRoot?: boolean }; |
| 72 | export const writeJSON = async ( |
no test coverage detected