如何转换/合并node.js / nconf中的configuration文件?

我有应用程序设置node.js应用程序和conf.json文件,即:

{ "settings": [ { "name": "setting1", "connectionString": { "host": "mongodb://127.0.0.1:27017/db", "collection": "collection1" } }, { "name": "setting2", "file": "/path/file", "token": "development token" } ] } 

有没有什么办法在Nconf或其他工具来模拟.NET的configuration转换,所以我可能有覆盖生产configuration文件,即conf.production.json:

 { "settings": [ { "name": "setting2", "token": "production token" } ] } 

生产模式中的“setting2”的期望值是“生产令牌”,并从默认configuration文件中rest。 我试图用nconf加载基本文件,但不起作用:

 nconf.file(process.env.NODE_ENV, './conf.' + process.env.NODE_ENV + '.json'); nconf.file('./conf.json'); 

我个人使用的configuration脚本的相关部分来处理这个问题:

 nconf .argv () .env () .defaults( require( './_config.js' ) ) .use ( 'memory' ) ; ... nconf.set( 'env' , nconf.get( 'environments:' + env ) ); nconf.set( 'env:name', env ); var includes = nconf.get( 'env:includes' ); if( {}.toString.call( includes ) === '[object Array]' ){ var incs = {}; includes.forEach( function( val ){ incs[ val ] = val; } ); includes = incs; } Object.keys( includes ).forEach( function( incName ){ var incPath = includes[ incName ] , incData = nconf.get( 'environments:' + incPath ); Object.keys( incData ).forEach( function( key ){ var keyNm = ( incName.indexOf( '__local' === 0 ) ) ? 'env:%s' .sprintf( key ) : 'env:%s:%s'.sprintf( incName, key ) ; if( nconf.get( keyNm ) == null ){ nconf.set( keyNm, incData[ key ] ); } }); } ); 

我认为那里唯一的依赖是sprintf ,你可以用npm安装,或者稍微重新设置代码。

基本上,我传入一个env参数,并将env设置.env对象。 然后我走一个includes对象,并从相同的configuration对象中拉入任何相关的JSON对象。

然后通过config.get( 'env:<param>' )访问所有内容

其中一个简单的config.js (我不喜欢.json因为它不能有评论)我使用的文件:

 module.exports = { environments : { libraries : { jQuery : '//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js' } , localLibraries : { jQuery : '/js/jquery-2.1.0.js' } , web_server : { task : 'web_server' , includes : [ 'cdn', 'libraries' ] , port : 12567 , csrfMaxAgeMs : 1000 * 60 * 60 * 24 * 30 // 30 days , csrfHashAlg : 'sha256' , apiHostName : '(^|\\.)api.*' , frontend : '/frontend' , jsonSpaces : 0 } , local_web_server : { task : 'web_server' , includes : { __local: 'web_server', libraries: 'localLibraries' } , jsonSpaces : 4 , dev : true } } }; 

您可以包含对象列表( ['cdn', 'libraries'] ),在这种情况下,它们将映射到env.cdn.param 。 或者你可以包含映射,如果键是__local ,它映射到当前对象。