options.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const os = require('os');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const assert = require('assert');
  6. const utils = require('egg-utils');
  7. const is = require('is-type-of');
  8. const deprecate = require('depd')('egg');
  9. module.exports = function(options) {
  10. const defaults = {
  11. framework: '',
  12. baseDir: process.cwd(),
  13. port: options.https ? 8443 : null,
  14. workers: null,
  15. plugins: null,
  16. https: false,
  17. };
  18. options = extend(defaults, options);
  19. if (!options.workers) {
  20. options.workers = os.cpus().length;
  21. }
  22. const pkgPath = path.join(options.baseDir, 'package.json');
  23. assert(fs.existsSync(pkgPath), `${pkgPath} should exist`);
  24. options.framework = utils.getFrameworkPath({
  25. baseDir: options.baseDir,
  26. // compatible customEgg only when call startCluster directly without framework
  27. framework: options.framework || options.customEgg,
  28. });
  29. const egg = require(options.framework);
  30. assert(egg.Application, `should define Application in ${options.framework}`);
  31. assert(egg.Agent, `should define Agent in ${options.framework}`);
  32. // https
  33. if (options.https) {
  34. if (is.boolean(options.https)) {
  35. // TODO: compatible options.key, options.cert, will remove at next major
  36. /* istanbul ignore next */
  37. deprecate('[master] Please use `https: { key, cert, ca }` instead of `https: true`');
  38. options.https = {
  39. key: options.key,
  40. cert: options.cert,
  41. };
  42. }
  43. assert(options.https.key && fs.existsSync(options.https.key), 'options.https.key should exists');
  44. assert(options.https.cert && fs.existsSync(options.https.cert), 'options.https.cert should exists');
  45. assert(!options.https.ca || fs.existsSync(options.https.ca), 'options.https.ca should exists');
  46. }
  47. options.port = parseInt(options.port, 10) || undefined;
  48. options.workers = parseInt(options.workers, 10);
  49. if (options.require) options.require = [].concat(options.require);
  50. // don't print depd message in production env.
  51. // it will print to stderr.
  52. if (process.env.NODE_ENV === 'production') {
  53. process.env.NO_DEPRECATION = '*';
  54. }
  55. const isDebug = process.execArgv.some(argv => argv.includes('--debug') || argv.includes('--inspect'));
  56. if (isDebug) options.isDebug = isDebug;
  57. return options;
  58. };
  59. function extend(target, src) {
  60. const keys = Object.keys(src);
  61. for (const key of keys) {
  62. if (src[key] != null) {
  63. target[key] = src[key];
  64. }
  65. }
  66. return target;
  67. }