config-manager.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const Fs = require('fs');
  2. const Path = require('path');
  3. /** 配置文件保存目录 */
  4. const configFileDir = 'local';
  5. /** 配置文件名 */
  6. const configFileName = 'ccc-png-auto-compress.json';
  7. /** 默认配置 */
  8. const defaultConfig = {
  9. enabled: false,
  10. minQuality: 40,
  11. maxQuality: 80,
  12. colors: 256,
  13. speed: 3,
  14. excludeFolders: [],
  15. excludeFiles: [],
  16. };
  17. /** 配置管理器 */
  18. const ConfigManager = {
  19. /**
  20. * 获取配置
  21. * @returns {object}
  22. */
  23. get() {
  24. const projectPath = Editor.Project.path || Editor.projectPath,
  25. configFilePath = Path.join(projectPath, configFileDir, configFileName);
  26. let config = null;
  27. if (Fs.existsSync(configFilePath)) {
  28. config = JSON.parse(Fs.readFileSync(configFilePath, 'utf8'));
  29. } else {
  30. config = { ...defaultConfig };
  31. }
  32. return config;
  33. },
  34. /**
  35. * 保存配置
  36. * @param {object} config 配置
  37. * @returns {string}
  38. */
  39. set(config) {
  40. // 查找目录
  41. const projectPath = Editor.Project.path || Editor.projectPath,
  42. configDirPath = Path.join(projectPath, configFileDir);
  43. if (!Fs.existsSync(configDirPath)) {
  44. Fs.mkdirSync(configDirPath);
  45. }
  46. const configFilePath = Path.join(projectPath, configFileDir, configFileName);
  47. // 读取本地配置
  48. let object = Object.create(null);
  49. if (Fs.existsSync(configFilePath)) {
  50. object = JSON.parse(Fs.readFileSync(configFilePath, 'utf8'));
  51. }
  52. // 写入配置
  53. for (const key in config) {
  54. let value = config[key];
  55. if (Array.isArray(value)) {
  56. value = value.filter(_value => _value !== '');
  57. }
  58. object[key] = value;
  59. }
  60. Fs.writeFileSync(configFilePath, JSON.stringify(object, null, 2));
  61. return configFilePath;
  62. },
  63. }
  64. module.exports = ConfigManager;