storage.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 storageDir = path.normalize('./storage/');
  9. exports.setup = function () {
  10. // const userDataDir = app.getPath('userData');
  11. // const storageDir = path.normalize(path.join(userDataDir, 'storage'));
  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('./storage/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;