index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const _ = require('lodash');
  2. const path = require('path');
  3. const fs = require('fs-extra');
  4. const branchFilename = __dirname + '/application_env';
  5. const propsToSave = [
  6. 'accessPassword',
  7. 'bookReadLink',
  8. 'loggingEnabled',
  9. 'maxFilesDirSize',
  10. 'queryCacheEnabled',
  11. 'cacheCleanInterval',
  12. 'inpxCheckInterval',
  13. 'lowMemoryMode',
  14. 'allowRemoteLib',
  15. 'remoteLib',
  16. 'server',
  17. ];
  18. let instance = null;
  19. //singleton
  20. class ConfigManager {
  21. constructor() {
  22. if (!instance) {
  23. this.inited = false;
  24. instance = this;
  25. }
  26. return instance;
  27. }
  28. async init(dataDir) {
  29. if (this.inited)
  30. throw new Error('already inited');
  31. this.branch = 'production';
  32. try {
  33. await fs.access(branchFilename);
  34. this.branch = (await fs.readFile(branchFilename, 'utf8')).trim();
  35. } catch (err) {
  36. //
  37. }
  38. process.env.NODE_ENV = this.branch;
  39. this.branchConfigFile = __dirname + `/${this.branch}.js`;
  40. const config = require(this.branchConfigFile);
  41. if (dataDir) {
  42. config.dataDir = path.resolve(dataDir);
  43. } else {
  44. config.dataDir = `${config.execDir}/.${config.name}`;
  45. }
  46. await fs.ensureDir(config.dataDir);
  47. this._userConfigFile = `${config.dataDir}/config.json`;
  48. this._config = config;
  49. this.inited = true;
  50. }
  51. get config() {
  52. if (!this.inited)
  53. throw new Error('not inited');
  54. return _.cloneDeep(this._config);
  55. }
  56. set config(value) {
  57. Object.assign(this._config, value);
  58. }
  59. get userConfigFile() {
  60. return this._userConfigFile;
  61. }
  62. set userConfigFile(value) {
  63. if (value)
  64. this._userConfigFile = value;
  65. }
  66. async load() {
  67. if (!this.inited)
  68. throw new Error('not inited');
  69. if (!await fs.pathExists(this.userConfigFile)) {
  70. await this.save();
  71. return;
  72. }
  73. const data = await fs.readFile(this.userConfigFile, 'utf8');
  74. this.config = JSON.parse(data);
  75. }
  76. async save() {
  77. if (!this.inited)
  78. throw new Error('not inited');
  79. const dataToSave = _.pick(this._config, propsToSave);
  80. await fs.writeFile(this.userConfigFile, JSON.stringify(dataToSave, null, 4));
  81. }
  82. }
  83. module.exports = ConfigManager;