[英]How to use nconf with flatiron properly
我正在嘗試使用flatiron構建一個小框架。 我想使用nconf加載我的所有配置文件,以便它們可以在我的應用程序中的任何位置使用。 在我的根目錄中,我有我的app.js,我想從config / bootstrap.js中獲取配置數據。
配置/配置/ JS
module.exports =
{ 'app' :
{ "host" : "localhost"
, "port" : process.env.port || 3000
}
}
bootstrap.js:
var nconf = require('nconf')
// database config
, dsource = require('./datasource')
// general or user config
, config = require('./config')
// allow overrides
nconf.overrides({
'always': 'be this value'
});
// add env vars and args
nconf.env().argv();
// load in configs from the config files
var defaults = {}
// so we can iterate over each config file
, confs = [dsource, config]
// for every config file
confs.forEach(function(conf)
{
// get each key
for (var key in conf)
{
// and add it to the defaults object
defaults[key] = conf[key]
}
})
// save the defaults object
nconf.defaults(defaults)
// logging this here works and properly shows the port setting
console.log('app port : ' + nconf.get('app:port'))
module.exports = nconf
所以當控制台從文件中記錄時。 一切似乎都很好。 但是,當我嘗試導出它,並從app.js需要它作為conf.get('app:port')它不起作用。
app.js(只是來自'flatiron create app'的香草app.js)
var flatiron = require('flatiron')
, app = flatiron.app
, path = require('path')
, conf = require('./config/bootstrap')
app.config.file({ file: path.join(__dirname, 'config', 'config.json') });
app.use(flatiron.plugins.http);
app.router.get('/', function () {
this.res.json({ 'hello': 'world' })
});
// this doesnt work, conf
app.start(conf.get('app:port'));
那么我怎樣才能讓它正常工作,以便在我的應用程序的任何地方都可以使用配置。 理想情況下,我希望能夠從app.config
類的任何地方獲得配置
這是使用nconf的最佳方式嗎? 我似乎找不到很多例子。 我看到的所有內容只是從實際的nconfig示例文件中提取配置信息。 不是來自app.config
之外的文件外部
或者我沒有正確使用它? 有沒有更好的方法來做到這一點。 理想情況下,我想使用此引導程序文件加載我的所有配置,以及資源/視圖(RVP樣式應用程序),所以它全部加載。
這是我對布局的一般想法,一個想法
|-- conf/
| |-- bootstrap.js
| |-- config.js
|-- resources
| |-- creature.js
|-- views/
|-- presenters/
|-- app.js
|-- package.json
您可以從任何有權訪問應用的地方獲得您的配置,如下所示:
app.config.get('google-maps-api-key')
如果你像這樣加載它:
app.config.file({ file: path.join(__dirname, 'config', 'config.json') })
這是加載JSON配置的正確方法:
nconf.use('file', {
file: process.cwd() + '/config.ini'
, format: nconf.formats.json
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.