storage.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 storageDir = path.normalize(os.homedir() + '/electron-egg-storage/');
  11. exports.setup = function () {
  12. // console.log('storageDir', storageDir);
  13. if (!fs.existsSync(storageDir)) {
  14. utils.mkdir(storageDir);
  15. utils.chmodPath(storageDir, '777');
  16. }
  17. const file = storageDir + 'db.json';
  18. const adapter = new FileSync(file);
  19. const db = lowdb(adapter);
  20. const eggConfigKey = storageKey.EGG_CONFIG;
  21. if (!db.has(eggConfigKey).value()) {
  22. db.set(eggConfigKey, {}).write();
  23. }
  24. return true;
  25. };
  26. exports.instance = function (file = null) {
  27. if (!file) {
  28. file = path.normalize(storageDir +'db.json');
  29. }
  30. const isExist = fs.existsSync(file);
  31. if (!isExist) {
  32. return null;
  33. }
  34. const adapter = new FileSync(file);
  35. const db = lowdb(adapter);
  36. return db;
  37. };
  38. exports.getEggConfig = function () {
  39. const key = storageKey.EGG_CONFIG;
  40. const res = this.instance()
  41. .get(key)
  42. .value();
  43. return res;
  44. };
  45. exports.setDynamicPort = async function () {
  46. // const eggConfig = config.get('egg');
  47. // console.log('setDynamicPort eggConfig:', eggConfig);
  48. // const dynamicPort = await getPort({port: eggConfig.port})
  49. const dynamicPort = await getPort();
  50. const key = storageKey.EGG_CONFIG + '.port';
  51. const res = this.instance()
  52. .set(key, dynamicPort)
  53. .write();
  54. return res;
  55. };
  56. exports.setIpcDynamicPort = async function () {
  57. const key = storageKey.ELECTRON_IPC + '.port';
  58. const dynamicPort = await getPort();
  59. this.instance()
  60. .set(key, dynamicPort)
  61. .write();
  62. return dynamicPort;
  63. };
  64. exports = module.exports;