-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathConfigFile.ts
More file actions
70 lines (58 loc) · 2.29 KB
/
ConfigFile.ts
File metadata and controls
70 lines (58 loc) · 2.29 KB
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
import { AppConfigData } from '@shared/config/interfaces';
import { getDefaultConfigData, overwriteConfigData } from '@back/config/util';
import { deepCopy, readJsonFile, readJsonFileSync, stringifyJsonDataFile } from '@shared/Util';
import * as fs from 'fs';
export namespace ConfigFile {
export function readFile(filePath: string, onError?: (error: string) => void): Promise<AppConfigData> {
return new Promise((resolve, reject) => {
readJsonFile(filePath, 'utf8')
.then(json => resolve(parse(json, onError)))
.catch(reject);
});
}
export function readFileSync(filePath: string, onError?: (error: string) => void): AppConfigData {
return parse(readJsonFileSync(filePath), onError);
}
export async function readOrCreateFile(filePath: string, onError?: (error: string) => void): Promise<AppConfigData> {
let error: Error | undefined;
let data: AppConfigData | undefined;
try {
data = await readFile(filePath, onError);
} catch (e: any) {
error = e;
}
if (error || !data) {
data = deepCopy(getDefaultConfigData(process.platform));
saveFile(filePath, data).catch(() => console.log('Failed to save default config file!'));
}
return data;
}
export function readOrCreateFileSync(filePath: string, onError?: (error: string) => void): AppConfigData {
let error: Error | undefined;
let data: AppConfigData | undefined;
try {
data = readFileSync(filePath, onError);
} catch (e: any) {
error = e;
}
if (error || !data) {
data = deepCopy(getDefaultConfigData(process.platform));
saveFile(filePath, data).catch(() => console.log('Failed to save default config file!'));
}
return data;
}
export function saveFile(filePath: string, data: AppConfigData): Promise<void> {
return new Promise((resolve, reject) => {
// Convert config to json string
const json: string = stringifyJsonDataFile(data);
// Save the config file
fs.writeFile(filePath, json, function(error) {
if (error) { return reject(error); }
else { return resolve(); }
});
});
}
function parse(json: any, onError?: (error: string) => void): AppConfigData {
return overwriteConfigData(deepCopy(getDefaultConfigData(process.platform)), json, onError);
}
}