config.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // electron/utils/readConfig.js
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { app } = require('electron');
  5. const package = require("../../package.json");
  6. const configPath = path.join(app.getPath("appData"), 'ZhiHuiYin', 'config.default.json');
  7. /**
  8. * 读取配置文件
  9. */
  10. function readConfigFile() {
  11. try {
  12. if (fs.existsSync(configPath)) {
  13. const data = fs.readFileSync(configPath, 'utf8');
  14. return JSON.parse(data);
  15. } else {
  16. console.log('配置文件不存在');
  17. // 创建空白JSON文件
  18. fs.writeFileSync(configPath, '{}', 'utf8');
  19. return {};
  20. }
  21. } catch (error) {
  22. console.error('读取配置文件出错:', error);
  23. return null;
  24. }
  25. }
  26. /**
  27. * 写入配置文件
  28. * @param {string} key - 要写入的配置项键名
  29. * @param {*} value - 要写入的配置项值
  30. */
  31. function writeConfigFile(key, value) {
  32. try {
  33. let config = {};
  34. // 如果配置文件存在,则读取现有内容
  35. if (fs.existsSync(configPath)) {
  36. const data = fs.readFileSync(configPath, 'utf8');
  37. config = JSON.parse(data);
  38. }else {
  39. console.log('配置文件不存在');
  40. // 创建空白JSON文件
  41. fs.writeFileSync(configPath, '{}', 'utf8');
  42. config = {}
  43. }
  44. // 更新配置项
  45. config[key] = value;
  46. // 将更新后的配置写回文件
  47. fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
  48. console.log(`成功写入配置项: ${key}`);
  49. } catch (error) {
  50. console.error('写入配置文件出错:', error);
  51. }
  52. }
  53. module.exports = {
  54. readConfigFile,
  55. writeConfigFile
  56. };