constatic
Version:
Constatic is a CLI for creating and managing modern TypeScript projects, providing an organized structure and features that streamline development.
77 lines (75 loc) • 1.78 kB
JavaScript
// src/lib/kvf.ts
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
class KeyValueFile {
data = {};
raw = "";
filepath;
constructor(filepath) {
this.filepath = filepath;
}
set(key, value) {
this.data[key] = value ?? "";
}
define(data, overwrite) {
if (overwrite) {
this.data = data;
return this;
}
this.data = {
...this.data,
...data
};
return this;
}
unset(key) {
this.data[key] = "";
}
delete(key) {
delete this.data[key];
}
get(key, fallback) {
return this.data[key] ?? fallback;
}
async read(path) {
const filepath = path ?? this.filepath;
if (!filepath) {
this.data = {};
return;
}
try {
this.raw = await readFile(filepath, "utf-8");
} catch {
this.raw = "";
}
this.data = KeyValueFile.parse(this.raw);
}
static parse(raw) {
const data = {};
const lines = raw.split(/\r?\n/);
for (const line of lines) {
if (!line || line.charAt(0) === "#" || line.charAt(0) === ";")
continue;
const [key, ...rest] = line.split("=");
if (!key)
continue;
data[key.trim()] = rest.join("=").trim();
}
return data;
}
async write(argA, argB) {
const filepath = typeof argA === "string" ? argA ?? this.filepath : this.filepath;
const noValues = typeof argA === "boolean" ? argA : argB;
if (!filepath)
return;
await mkdir(dirname(filepath), { recursive: true });
await writeFile(filepath, this.toString(noValues), "utf-8");
}
toString(noValues = false) {
return Object.entries(this.data).map(([key, value]) => noValues ? `${key}=` : `${key}=${value ?? ""}`).join(`
`);
}
}
export {
KeyValueFile
};