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