浏览代码

动态端口,统一config

gaoshuaixing 5 年之前
父节点
当前提交
9cae92d069
共有 6 个文件被更改,包括 150 次插入52 次删除
  1. 9 4
      config/config.default.js
  2. 26 2
      electron/config.js
  3. 1 5
      electron/lanucher.js
  4. 5 3
      electron/setup.js
  5. 64 0
      electron/storage.js
  6. 45 38
      main.js

+ 9 - 4
config/config.default.js

@@ -2,7 +2,7 @@
 
 'use strict';
 const path = require('path');
-const electronConfig = require('../electron/config').get()
+const electronEggConfig = require('../electron/config').get('web-egg');
 
 /**
  * @param {Egg.EggAppInfo} appInfo app info
@@ -27,8 +27,8 @@ module.exports = appInfo => {
 
   config.cluster = {
     listen: {
-      port: electronConfig.egg.port || 7068,
-      hostname: electronConfig.egg.hostname || '0.0.0.0',
+      port: electronEggConfig.port || 7068,
+      hostname: electronEggConfig.hostname || '0.0.0.0',
       // path: '/var/run/egg.sock',
     },
   };
@@ -91,9 +91,14 @@ module.exports = appInfo => {
   };
 
   config.ejs = {};
-
+  //getPort();
   return {
     ...config,
     ...userConfig,
   };
 };
+
+// function getPort () {
+//   const dbFile = path.normalize('./storage/db.json');
+//   console.log('dbFile:', dbFile);
+// }

+ 26 - 2
electron/config.js

@@ -2,6 +2,7 @@
 
 const path = require('path');
 const dayjs = require('dayjs');
+const storage = require('./storage');
 
 const config = {
   log: {
@@ -34,8 +35,31 @@ const config = {
   }
 }
 
-exports.get = function () {
-  return config;
+exports.get = function (flag = '') {
+  console.log('config flag:', flag);
+  if (flag === 'log') {
+    return config.log;
+  }
+
+  if (flag === 'windowsOption') {
+    return config.windowsOption;
+  }
+
+  if (flag === 'web-egg') {
+    return config.egg;
+  }
+
+  if (flag === 'egg') {
+    const eggConfig = storage.getEggConfig();
+    console.log('eggConfig:', eggConfig);
+    if (eggConfig.port) {
+      console.log('eggConfig.port:', eggConfig.port);
+      config.egg.port = eggConfig.port;
+    }
+    return config.egg;
+  }
+  
+  return {};
 };
 
 exports = module.exports;

+ 1 - 5
electron/lanucher.js

@@ -44,11 +44,7 @@ exports.start = function (argv) {
     const ignoreKeys = [ '_', '$0', 'env', 'daemon', 'stdout', 'stderr', 'timeout', 'ignore-stderr', 'node' ];
     const clusterOptions = stringify(argv, ignoreKeys);
     const options = JSON.parse(clusterOptions);
-    // console.log('options:', {
-    //   argv,
-    //   options
-    // });
-
+    console.log('[lanucher] options:', options)
     return new Promise((resolve, reject) => {
       startCluster(options, function(){
         resolve('success');

+ 5 - 3
electron/setup.js

@@ -1,14 +1,16 @@
 'use strict';
 
-global.ELog = require('electron-log')
-const config = require('./config')
+global.ELog = require('electron-log');
+const storage = require('./storage');
+const config = require('./config');
 
 module.exports = () => {
+  storage.setup();
   logger();
 }
 
 function logger () {
-  let logConfig = config.get().log;
+  let logConfig = config.get('log');
   for (let transport in logConfig) {
     const configInfo = logConfig[transport];
     if (transport === 'file') {

+ 64 - 0
electron/storage.js

@@ -0,0 +1,64 @@
+'use strict';
+
+const path = require('path');
+const lowdb = require('lowdb');
+const FileSync = require('lowdb/adapters/FileSync');
+const fs = require('fs');
+const getPort = require('get-port');
+const utils = require('../app/utils/utils');
+const config = require('./config');
+
+const storageDir = path.normalize('./storage/');
+
+exports.setup = function () {
+  if (!fs.existsSync(storageDir)) {
+    utils.mkdir(storageDir);
+    utils.chmodPath(storageDir, '777');
+  }
+  const file = storageDir + 'db.json';
+  const adapter = new FileSync(file);
+  const db = lowdb(adapter);
+
+  if (!db.has('egg_config').value()) {
+    db.set('egg_config', {}).write();
+  }
+
+  return true;
+};
+
+exports.instance = function (file = null) {
+  if (!file) {
+      file = path.normalize('./storage/db.json');
+  }
+  const isExist = fs.existsSync(file);
+  if (!isExist) {
+      return null;
+  }
+
+  const adapter = new FileSync(file);
+  const db = lowdb(adapter);
+
+  return db;
+};
+
+exports.getEggConfig = function () {
+  const res = this.instance()
+  .get('egg_config')
+  .value();
+
+  return res;
+};
+
+exports.setDynamicPort = async function () {
+  const eggConfig = config.get('egg');
+  console.log('setDynamicPort eggConfig:', eggConfig);
+  // const dynamicPort = await getPort({port: eggConfig.port})
+  const dynamicPort = await getPort();
+  const res = this.instance()
+    .set('egg_config.port', dynamicPort)
+    .write();
+  
+  return res;
+};
+
+exports = module.exports;

+ 45 - 38
main.js

@@ -1,25 +1,20 @@
 const {app, BrowserWindow, Menu, shell} = require('electron')
 const path = require('path')
-const getPort = require('get-port')
 const eggLauncher = require('./electron/lanucher')
 const setup = require('./electron/setup')
-const config = require('./electron/config').get()
+const electronConfig = require('./electron/config')
+const storage = require('./electron/storage')
 
+// Initialize 
 setup()
+// return
 
-//return
-// 主窗口
+// main window
 global.MAIN_WINDOW = null
 
-for (let i = 0; i < process.argv.length; i++) {
-  const tmpArgv = process.argv[i]
-  if (tmpArgv.indexOf('--env=') !== -1) {
-    config.egg.env = tmpArgv.substr(6)
-  }
-}
-
 if (process.mas) app.setName('electron-egg')
 
+// Open url with the default browser
 app.on('web-contents-created', (e, webContents) => {
     webContents.on('new-window', (event, url) => {
         event.preventDefault()
@@ -27,24 +22,55 @@ app.on('web-contents-created', (e, webContents) => {
     });
 });
 
+async function initialize () {
+
+  // dynamic port
+  await storage.setDynamicPort();
+  
+  app.whenReady().then(() => {
+    createWindow()
+    app.on('activate', function () {
+      if (BrowserWindow.getAllWindows().length === 0) {
+        createWindow()
+      }
+    })
+  })
+  
+  app.on('window-all-closed', function () {
+    if (process.platform !== 'darwin') {
+      console.log('window-all-closed quit')
+      app.quit()
+    }
+  })
+}
+
 async function createWindow () {
-  MAIN_WINDOW = new BrowserWindow(config.windowsOption)
+  // argv
+  const eggConfig = electronConfig.get('egg')
+  for (let i = 0; i < process.argv.length; i++) {
+    const tmpArgv = process.argv[i]
+    if (tmpArgv.indexOf('--env=') !== -1) {
+      eggConfig.env = tmpArgv.substr(6)
+    }
+  }
 
+  MAIN_WINDOW = new BrowserWindow(electronConfig.get('windowsOption'))
+  
   // if (process.platform === 'linux') {
   //   windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
   // }
 
-  if (config.egg.env === 'prod') {
-    //隐藏菜单
+  if (eggConfig.env === 'prod') {
+    // hidden menu
     Menu.setApplicationMenu(null)
   }
 
-  // loding页
+  // loding page
   MAIN_WINDOW.loadURL(path.join('file://', __dirname, '/app/public/loading.html'))
   
-  // egg服务
+  // egg server
   setTimeout(function(){
-    startServer(config.egg)
+    startServer(eggConfig)
   }, 100)
 
   return MAIN_WINDOW
@@ -52,35 +78,16 @@ async function createWindow () {
 
 async function startServer (options) {
   let startRes = null
-  options.port = await getPort({port: options.port})
-  ELog.info('config.egg', options)
+  ELog.info('[main] [startServer] options', options)
   startRes = await eggLauncher.start(options).then((res) => res, (err) => err)
   ELog.info('startRes:', startRes)
   if (startRes === 'success') {
     let url = 'http://localhost:' + options.port
     MAIN_WINDOW.loadURL(url)
 
-    return
+    return true
   }
   app.relaunch()
-} 
-
-async function initialize () {
-  app.whenReady().then(() => {
-    createWindow()
-    app.on('activate', function () {
-      if (BrowserWindow.getAllWindows().length === 0) {
-        createWindow()
-      }
-    })
-  })
-  
-  app.on('window-all-closed', function () {
-    if (process.platform !== 'darwin') {
-      console.log('window-all-closed quit')
-      app.quit()
-    }
-  })
 }
 
 initialize()