pomelo源码分析(1)
一、app init
首先我们来分析一下
// at app.ts
var app = pinus.createApp();
紧接着会调用 app.init(opts) 初始化
// at pinus.ts
createApp(opts ?: ApplicationOptions) {
let app = new Application();
app.init(opts);
this._app = app;
return app;
}
继续往下看
// at application.ts
init(opts ?: ApplicationOptions) {
opts = opts || {
};
let base = opts.base || process.cwd();
this.set(Constants.RESERVED.BASE, base);
this.base = base;
appUtil.defaultConfiguration(this);
this.state = STATE_INITED;
logger.info('application inited: %j', this.getServerId());
}
我们重点看appUtil.defaultConfiguration(this)
// at appUitl.ts
export function defaultConfiguration(app: Application) {
// Parse command line arguments
let args = parseArgs(process.argv);
// Setup enviroment
setupEnv(app, args);
// Load master info from config/master.json.
loadMaster(app);
// Load server info from config/servers.json.
loadServers(app);
// Process server start command
processArgs(app, args);
// Configure custom logger
configLogger(app);
// Load lifecycle file.
loadLifecycle(app);
}
可以看到 最后初始化其实干了这些事 我们来依次分析一下。
1.passeArgs
这个方法官方注释的解释是Parse command line arguments,解析命令行参数。我在本地调试的时候,process.argv的值是一个由2个元素组成的数组[“C:\Program Files\nodejs\node.exe”,“D:\code\project\dist\app.js”],方法最后返回一个字符串"D:\code\project\dist\app.js"。
2.setupEnv(app, args)
设置环境
3.loadMaster(app)
往下看代码
// at appUitl.ts
let loadMaster = function (app: Application) {
// Constants.RESERVED.MASTER = 'master'
// Constants.FILEPATH.MASTER = '/config/master.json'
app.loadConfigBaseApp(Constants.RESERVED.MASTER, Constants.FILEPATH.MASTER);
app.master = app.get(Constants.RESERVED.MASTER);
};
// at application.ts
loadConfigBaseApp(key: string, val: string, reload = false) {
let self = this;
let env = this.get(Constants.RESERVED.ENV);
let originPath = path.join(this.getBase(), val);
let presentPath = path.join(this.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(val));