files.tsā¢1.67 kB
import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseJsonc, parseTree as parseJsoncTree, modify as modifyJsonc } from "jsonc-parser";
import { parse as parseYaml, stringify as dumpYaml } from "yaml";
import * as TOML from "@iarna/toml";
import { parse as parseCommentJson, stringify as stringifyCommentJson } from "comment-json";
export type SupportedFormats = "json" | "jsonc" | "yaml" | "yml" | "toml";
function detectFormat(file: string): SupportedFormats {
const ext = path.extname(file).toLowerCase().replace(/^\./, "");
if (ext === "yml") return "yml";
if (ext === "yaml") return "yaml";
if (ext === "toml") return "toml";
if (ext === "jsonc") return "jsonc";
return "json";
}
export async function readConfigFile(file: string): Promise<any> {
const fmt = detectFormat(file);
const content = await fs.readFile(file, "utf8");
switch (fmt) {
case "yaml":
case "yml":
return parseYaml(content);
case "toml":
return TOML.parse(content);
case "jsonc":
return parseCommentJson(content);
case "json":
default:
return JSON.parse(content);
}
}
export async function writeConfigFile(file: string, data: any): Promise<void> {
const fmt = detectFormat(file);
let content: string;
switch (fmt) {
case "yaml":
case "yml":
content = dumpYaml(data);
break;
case "toml":
content = TOML.stringify(data as any);
break;
case "jsonc":
content = stringifyCommentJson(data, null, 2);
break;
case "json":
default:
content = JSON.stringify(data, null, 2);
}
await fs.writeFile(file, content, "utf8");
}