storage.js 1.5 KB

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