我一直在开发一些Node应用程序,我一直在寻找一种存储部署相关设置的良好模式。在Django世界(我来自那里),常见的做法是有一个settings.py文件包含标准设置(时区等),然后有一个local_settings.py用于部署特定的设置,即。要与什么数据库通信、什么memcache套接字、管理员的电子邮件地址等等。

我一直在为Node寻找类似的模式。只要一个配置文件就好了,这样它就不必与app.js中的其他所有东西挤在一起,但我发现有一种方法在源代码控制之外的文件中拥有特定于服务器的配置很重要。同一款应用可以部署在不同设置的服务器上,必须处理合并冲突,这不是我的乐趣所在。

那么是否存在某种框架/工具,或者每个人都只是自己拼凑一些东西?


当前回答

很久以后,我发现了一个非常好的Node.js模块来管理配置:nconf。

举个简单的例子:

var nconf = require('nconf');

// First consider commandline arguments and environment variables, respectively.
nconf.argv().env();

// Then load configuration from a designated file.
nconf.file({ file: 'config.json' });

// Provide default values for settings not provided above.
nconf.defaults({
    'http': {
        'port': 1337
    }
});

// Once this is in place, you can just use nconf.get to get your settings.
// So this would configure `myApp` to listen on port 1337 if the port
// has not been overridden by any of the three configuration inputs
// mentioned above.
myApp.listen(nconf.get('http:port'));

它还支持在Redis中存储设置,编写配置文件,并且有一个相当可靠的API,并且还得到了一个更受尊敬的Node.js商店Nodejitsu的支持,作为Flatiron框架计划的一部分,所以它应该是相当经得起未来的。

在Github上查看nconf。

其他回答

只需要用exports做一个简单的settings.js:

exports.my_password = 'value'

然后,在你的脚本中,执行require:

var settings = require('./settings.js');

所有的设置现在将可用的设置变量:

settings.my_password // 'value'

我用一个包装。Json为我的包和config.js为我的配置,它看起来像:

var config = {};

config.twitter = {};
config.redis = {};
config.web = {};

config.default_stuff =  ['red','green','blue','apple','yellow','orange','politics'];
config.twitter.user_name = process.env.TWITTER_USER || 'username';
config.twitter.password=  process.env.TWITTER_PASSWORD || 'password';
config.redis.uri = process.env.DUOSTACK_DB_REDIS;
config.redis.host = 'hostname';
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;

module.exports = config;

我从我的项目加载配置:

var config = require('./config');

然后我可以从config.db_host, config.db_port等访问我的东西…这让我可以使用硬编码的参数,如果我不想在源代码控制中存储密码,也可以使用存储在环境变量中的参数。

我还生成了一个包。Json和插入依赖项部分:

"dependencies": {
  "cradle": "0.5.5",
  "jade": "0.10.4",
  "redis": "0.5.11",
  "socket.io": "0.6.16",
  "twitter-node": "0.0.2",
  "express": "2.2.0"
}

当我将项目克隆到本地机器时,我运行npm install来安装包。更多信息请点击这里。

项目存储在GitHub中,并为我的生产服务器添加了遥控器。

最好将“开发”和“生产”配置分开。

我用以下方法: 这是我的config/index.js文件:

const config = {
    dev : {
        ip_address : '0.0.0.0',
        port : 8080,
        mongo :{
            url : "mongodb://localhost:27017/story_box_dev",
            options : ""
        }
    },
    prod : {
        ip_address : '0.0.0.0',
        port : 3000,
        mongo :{
            url : "mongodb://localhost:27017/story_box_prod",
            options : ""
        }
    }
} 

对于require配置使用如下:

const config = require('../config')[process.env.NODE_ENV];

然后你可以使用你的配置对象:

const ip_address = config.ip_address;
const port = config.port;

我最近刚刚发布了一个小模块来加载任何类型的配置文件。 它非常简单,你可以在https://github.com/flesler/config-node上查看

对于那些正在访问这个旧线程的人来说,这里有一个我觉得不错的包。

https://www.npmjs.org/package/config