config.js 1.5 KB

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