import fs from "fs"; import os from "os"; import path from "path"; import { promisify } from "util"; import { logger } from "./logger"; const configDirName = ".HelloWorld"; /** * 用来管理配置文件 * 方便按照模块存储配置文件到$HOMEDIR/${configDirName}文件夹中 */ export class ConfigManager { module: string; configDir: string; configFile: string; config: T; defaultValue: T; constructor(module: string, defaultValue: T) { this.module = module; this.defaultValue = defaultValue; this.config = defaultValue; this.configDir = path.join(os.homedir(), configDirName); this.configFile = path.join(this.configDir, `${this.module}.json`); } static create = async (module: string, defaultValue: T) => { const c = new ConfigManager(module, defaultValue); await c.init(); return c; }; init = async () => { await this.sureConfig(); await this.load(); }; sureConfig = async () => { try { await promisify(fs.access)(this.configDir); } catch (error) { logger.log(`配置文件目录${this.configDir}不存在`); logger.log(`创建目录`); await promisify(fs.mkdir)(this.configDir, { recursive: true }); } try { await promisify(fs.access)(this.configFile); } catch (error) { logger.log(`配置文件${this.configFile}不存在`); logger.log(`创建配置文件`); await promisify(fs.writeFile)( this.configFile, JSON.stringify(this.defaultValue, null, 4), { flag: "w" } ); } }; load = async () => { try { this.config = JSON.parse( (await promisify(fs.readFile)(this.configFile)).toString() ); } catch (error) { logger.log(`读取${this.module}配置文件失败`); this.config = this.defaultValue; } }; save = async () => { try { await promisify(fs.writeFile)( this.configFile, JSON.stringify(this.config, null, 4), { flag: "w" } ); } catch (error) { logger.log(`写入${this.module}配置文件失败`); } }; setValue = async (key: K, value: T[K]) => { this.config[key] = value; await this.save(); }; setValues = async (changes: Partial) => { this.config = { ...this.config, ...changes }; await this.save(); }; getValues = () => this.config; } export const mainConfigManager = new ConfigManager("main", {});