*add api to read files from dir and parse as JSON

This commit is contained in:
Derrick Hammer 2022-09-21 15:46:01 -04:00
parent 82dddc75cf
commit 334078669a
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 40 additions and 1 deletions

View File

@ -116,6 +116,7 @@ class Config {
this.prefix = this.getPrefix(); this.prefix = this.getPrefix();
} }
public open(file: string) { public open(file: string) {
const path = this.getFile(file); const path = this.getFile(file);
@ -132,6 +133,45 @@ class Config {
this.prefix = this.getPrefix(); this.prefix = this.getPrefix();
} }
public openDir(dir: string) {
assert(fs.existsSync(dir), `Directory ${dir} does not exist`);
let files = fs.readdirSync(dir).map((item) => Path.join(dir, item));
files.forEach(this.openJson);
}
public openJson(file: string) {
const path = this.getFile(file);
let json;
try {
json = fs.readFileSync(path, "utf8");
json = JSON.parse(json);
} catch (e) {
if (e.code === "ENOENT") return;
throw e;
}
assert(typeof json === "object", `Config file ${file} must be an object`);
for (const key of Object.keys(json)) {
const value = json[key];
switch (value) {
case Array.isArray(value):
let newVal = this.array(key) ?? [];
newVal.push(value);
this.set(key, newVal);
break;
default:
this.set(key, value);
break;
}
}
this.prefix = this.getPrefix();
}
public filter(name: string) { public filter(name: string) {
assert(typeof name === "string"); assert(typeof name === "string");
@ -475,7 +515,6 @@ class Config {
const parts = value.trim().split(/\s*,\s*/); const parts = value.trim().split(/\s*,\s*/);
const result = []; const result = [];
``;
for (const part of parts) { for (const part of parts) {
if (part.length === 0) { if (part.length === 0) {
continue; continue;