config.js 1.7 KB

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