configJS
快速开始
$ npm install config
$ mkdir config
$ vi config/default.json
{
// Customer module configs
"Customer": {
"dbConfig": {
"host": "localhost",
"port": 5984,
"dbName": "customers"
},
"credit": {
"initialLimit": 100,
// Set low for development
"initialDays": 1
}
}
}
$ vi config/production.json
{
"Customer": {
"dbConfig": {
"host": "prod-db-server"
},
"credit": {
"initialDays": 30
}
}
}
my-app.js
const config = require('config');
//config.get() will throw an exception for undefined keys to help catch typos and ??missing values.
//Use config.has() to test if a configuration value is defined.
var dbConfig = config.get('Customer.dbConfig'); //和下面方法获得一样的结果
var dbConfig2 = config.Customer.dbConfig
console.log(dbConfig);
console.log('-----------'); console.log(dbConfig2);
如果这个时候运行 node my-app.js的话,结果如下
{ host: 'localhost', port: 5984, dbName: 'customers' }
-----------
{ host: 'localhost', port: 5984, dbName: 'customers' }
假如我们改变一点点
$ export NODE_ENV=production
$ node my-app.js
结果将会
{ host: 'prod-db-server', port: 5984, dbName: 'customers' }
-----------
{ host: 'prod-db-server', port: 5984, dbName: 'customers' }
Running in this configuration, the port and dbName elements of dbConfig will come from the default.json file, and the host element will come from the production.json override file.