Procházet zdrojové kódy

feat(electron): 添加配置文件读写功能并应用于 utils.js

- 新增 config.js 文件,实现配置文件的读取和写入功能
- 在 utils.js 中引入并使用配置文件读取功能
- 修改 utils.js 中的窗口加载逻辑,根据配置文件决定是否打开开发者工具
panqiuyao před 5 měsíci
rodič
revize
44850ab74a
2 změnil soubory, kde provedl 71 přidání a 1 odebrání
  1. 4 1
      electron/controller/utils.js
  2. 67 0
      electron/utils/config.js

+ 4 - 1
electron/controller/utils.js

@@ -8,6 +8,9 @@ const fs = require('fs');
 const path = require('path');
 const CoreWindow = require('ee-core/electron/window');
 const { BrowserWindow, Menu } = require('electron');
+
+const { readConfigFile } = require('../utils/config');
+const configDeault = readConfigFile();
 const errData = {
   msg :'请求失败,请联系管理员',
   code:999
@@ -69,7 +72,7 @@ class UtilsController extends Controller {
     });
     await win.loadURL(config.url); // 设置窗口的 URL
     // 监听窗口关闭事件
-    if(this.app?.env === 'development')  win.webContents.openDevTools(config.openDevTools)
+    if(configDeault.openDevTools)  win.webContents.openDevTools(config.openDevTools)
    //
     win.on('close', () => {
       delete this.app.electron[config.id]; // 删除窗口引用

+ 67 - 0
electron/utils/config.js

@@ -0,0 +1,67 @@
+// electron/utils/readConfig.js
+
+const fs = require('fs');
+const path = require('path');
+const { app } = require('electron');
+
+const package  =  require("../../package.json");
+const configPath = path.join(app.getPath("appData"), 'ZhiHuiYin', 'config.default.json');
+
+
+/**
+ * 读取配置文件
+ */
+function readConfigFile() {
+
+  try {
+    if (fs.existsSync(configPath)) {
+      const data = fs.readFileSync(configPath, 'utf8');
+      return JSON.parse(data);
+    } else {
+      console.log('配置文件不存在');
+      // 创建空白JSON文件
+      fs.writeFileSync(configPath, '{}', 'utf8');
+      return {};
+    }
+  } catch (error) {
+    console.error('读取配置文件出错:', error);
+    return null;
+  }
+}
+
+/**
+ * 写入配置文件
+ * @param {string} key - 要写入的配置项键名
+ * @param {*} value - 要写入的配置项值
+ */
+function writeConfigFile(key, value) {
+
+  try {
+    let config = {};
+
+    // 如果配置文件存在,则读取现有内容
+    if (fs.existsSync(configPath)) {
+      const data = fs.readFileSync(configPath, 'utf8');
+      config = JSON.parse(data);
+    }else {
+      console.log('配置文件不存在');
+      // 创建空白JSON文件
+      fs.writeFileSync(configPath, '{}', 'utf8');
+      config = {}
+    }
+
+    // 更新配置项
+    config[key] = value;
+
+    // 将更新后的配置写回文件
+    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
+    console.log(`成功写入配置项: ${key}`);
+  } catch (error) {
+    console.error('写入配置文件出错:', error);
+  }
+}
+
+module.exports = {
+  readConfigFile,
+  writeConfigFile
+};