为不同的环境使用不同的 PropertiesConfiguration,例如 dev qa staging 等
大规模应用程序在不同环境中运行时通常需要不同的属性。我们可以通过将参数传递给 NodeJs 应用程序并在节点进程中使用相同的参数来加载特定的环境属性文件来实现这一点。
假设我们有两个不同环境的属性文件。
-
dev.json
{ "PORT": 3000, "DB": { "host": "localhost", "user": "bob", "password": "12345" } }
-
qa.json
{ "PORT": 3001, "DB": { "host": "where_db_is_hosted", "user": "bob", "password": "54321" } }
应用程序中的以下代码将导出我们想要使用的相应属性文件。
process.argv.forEach(function (val) {
var arg = val.split("=");
if (arg.length > 0) {
if (arg[0] === 'env') {
var env = require('./' + arg[1] + '.json');
exports.prop = env;
}
}
});
我们为应用程序提供如下参数
node app.js env=dev
如果我们使用进程管理器一样永远比它那样简单
forever start app.js env=dev