storage.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. const path = require('path');
  3. const lowdb = require('lowdb');
  4. const FileSync = require('lowdb/adapters/FileSync');
  5. const fs = require('fs');
  6. const getPort = require('get-port');
  7. const utils = require('../app/utils/utils');
  8. const storageKey = require('../app/const/storageKey');
  9. const os = require('os');
  10. const pkg = require('../package.json');
  11. const storageDir = path.normalize(os.userInfo().homedir + '/' + pkg.name + '/');
  12. const storageDb = 'db.json';
  13. exports.setup = function () {
  14. // console.log('storageDir', storageDir);
  15. if (!fs.existsSync(storageDir)) {
  16. utils.mkdir(storageDir);
  17. utils.chmodPath(storageDir, '777');
  18. }
  19. const file = storageDir + storageDb;
  20. const adapter = new FileSync(file);
  21. const db = lowdb(adapter);
  22. const eggConfigKey = storageKey.EGG_CONFIG;
  23. if (!db.has(eggConfigKey).value()) {
  24. db.set(eggConfigKey, {}).write();
  25. }
  26. return true;
  27. };
  28. exports.instance = function (file = null) {
  29. if (!file) {
  30. file = path.normalize(storageDir + storageDb);
  31. }
  32. const isExist = fs.existsSync(file);
  33. if (!isExist) {
  34. return null;
  35. }
  36. const adapter = new FileSync(file);
  37. const db = lowdb(adapter);
  38. return db;
  39. };
  40. exports.getEggConfig = function () {
  41. const key = storageKey.EGG_CONFIG;
  42. const res = this.instance()
  43. .get(key)
  44. .value();
  45. return res;
  46. };
  47. exports.setDynamicPort = async function () {
  48. // const eggConfig = config.get('egg');
  49. // console.log('setDynamicPort eggConfig:', eggConfig);
  50. // const dynamicPort = await getPort({port: eggConfig.port})
  51. const dynamicPort = await getPort();
  52. const key = storageKey.EGG_CONFIG + '.port';
  53. const res = this.instance()
  54. .set(key, dynamicPort)
  55. .write();
  56. return res;
  57. };
  58. exports.setIpcDynamicPort = async function () {
  59. const key = storageKey.ELECTRON_IPC + '.port';
  60. const dynamicPort = await getPort();
  61. this.instance()
  62. .set(key, dynamicPort)
  63. .write();
  64. return dynamicPort;
  65. };
  66. exports = module.exports;