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

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

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


当前回答

我用一个包装。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中加载环境配置

var env = process.env.NODE_ENV || 'development'
  , cfg = require('./config.'+env);

module.exports = cfg;

在./config/config.global.js中定义一些默认值

var config = module.exports = {};

config.env = 'development';
config.hostname = 'dev.example.com';

//mongo database
config.mongo = {};
config.mongo.uri = process.env.MONGO_URI || 'localhost';
config.mongo.db = 'example_dev';

重写。/config/config.test.js中的默认值

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

config.env = 'test';
config.hostname = 'test.example';
config.mongo.db = 'example_test';

module.exports = config;

在./models/user.js中使用:

var mongoose = require('mongoose')
, cfg = require('../config')
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);

在测试环境中运行应用程序:

NODE_ENV=test node ./app.js

我在这里尝试了一些建议的解决方案,但对它们不满意,所以我创建了自己的模块。它被称为微配置,主要的区别是它尊重约定而不是配置,所以你可以只需要这个模块并开始使用它。

你存储你的配置在纯js,或json文件从/config文件夹。首先它加载default.js文件,然后是/config目录下的所有其他文件,然后它根据$NODE_ENV变量加载特定于环境的配置。

它还允许使用local.js或特定于环境的/config/env/$NODE_ENV.local.js覆盖本地开发的配置。

你可以在这里看看:

https://www.npmjs.com/package/mikro-config

https://github.com/B4nan/mikro-config

您可以从Node v0.5开始要求JSON文件。X(引用这个答案)

json:

{
    "username" : "root",
    "password" : "foot"
}

app.js:

var config = require('./config.json');
log_in(config.username, config.password);

我在游戏中有点晚了,但我在这里或其他地方都找不到我需要的东西,所以我自己写了一些东西。

我对配置机制的要求如下:

支持前端。如果前端不能使用该配置有什么意义? 支持settings-override .js -看起来一样,但允许重写settings.js中的配置。这里的思想是在不更改代码的情况下轻松修改配置。我发现它对saas很有用。

尽管我不太关心支持环境,但它将解释如何轻松地将其添加到我的解决方案中

var publicConfiguration = {
    "title" : "Hello World"
    "demoAuthToken" : undefined, 
    "demoUserId" : undefined, 
    "errorEmail" : null // if null we will not send emails on errors. 

};

var privateConfiguration = {
    "port":9040,
    "adminAuthToken":undefined,
    "adminUserId":undefined
}

var meConf = null;
try{
    meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}




var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;

function getPublicConfiguration(){
    if (!publicConfigurationInitialized) {
        publicConfigurationInitialized = true;
        if (meConf != null) {
            for (var i in publicConfiguration) {
                if (meConf.hasOwnProperty(i)) {
                    publicConfiguration[i] = meConf[i];
                }
            }
        }
    }
    return publicConfiguration;
}


function getPrivateConfiguration(){
    if ( !privateConfigurationInitialized ) {
        privateConfigurationInitialized = true;

        var pubConf = getPublicConfiguration();

        if ( pubConf != null ){
            for ( var j in pubConf ){
                privateConfiguration[j] = pubConf[j];
            }
        }
        if ( meConf != null ){
              for ( var i in meConf ){
                  privateConfiguration[i] = meConf[i];
              }
        }
    }
    return privateConfiguration;

}


exports.sendPublicConfiguration = function( req, res ){
    var name = req.param("name") || "conf";

    res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};


var prConf = getPrivateConfiguration();
if ( prConf != null ){
    for ( var i in prConf ){
        if ( prConf[i] === undefined ){

            throw new Error("undefined configuration [" + i + "]");
        }
        exports[i] = prConf[i];
    }
}


return exports;

解释

undefined means this property is required null means it is optional meConf - currently the code is target to a file under app. meConf is the overrides files which is targeted to conf/dev - which is ignored by my vcs. publicConfiguration - will be visible from front-end and back-end. privateConfiguration - will be visible from back-end only. sendPublicConfiguration - a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf. app.get("/backend/conf", require("conf").sendPublicConfiguration);

覆盖逻辑

privateConfiguration与publicConfiguration和meConf合并。 publicConfiguration检查每个键是否有覆盖,并使用该覆盖。这样我们就不会暴露任何隐私。

添加环境支持

即使我不觉得“环境支持”有用,也许有人会。

要添加环境支持,您需要将meConf require语句更改为以下内容(伪代码)

If (environment == "production") { meConf = require("../conf/dev/meConf").production; }

If (environment == "development") { meConf = require("../conf/dev/meConf").development; }

类似地,每个环境可以有一个文件

 meConf.development.js
 meConf.production.js

然后导入正确的。 其余的逻辑保持不变。

在这里,我将全身心地投入其中,因为这些答案中没有一个解决了几乎任何系统都需要的所有关键组件。注意事项:

公共配置(可以从前端看到)vs私有配置(guy mograbi说对了)。并确保它们是分开的。 钥匙一样的秘密 默认值vs特定于环境的覆盖 前端包

以下是我如何进行配置:

config.default.private.js - In version control, these are default configuration options that can only be seen by your backend. config.default.public.js - In version control, these are default configuration options that can be seen by backend and frontend config.dev.private.js - If you need different private defaults for dev. config.dev.public.js - If you need different public defaults for dev. config.private.js - Not in version control, these are environment specific options that override config.default.private.js config.public.js - Not in version control, these are environment specific options that override config.default.public.js keys/ - A folder where each file stores a different secret of some kind. This is also not under version control (keys should never be under version control).

I use plain-old javascript files for configuration so I have the full power of the javascript langauge (including comments and the ability to do things like load the default config file in the environment-specific file so they can then be overridden). If you want to use environment variables, you can load them inside those config files (tho I recommend against using env vars for the same reason I don't recommend using json files - you don't have the power of a programming language to construct your config).

每个键在一个单独的文件中的原因是为了安装程序的使用。这允许您有一个安装程序,在机器上创建密钥并将它们存储在密钥文件夹中。如果不这样做,当你加载无法访问密钥的配置文件时,安装程序可能会失败。通过这种方式,您可以遍历目录并加载该文件夹中的任何关键文件,而不必担心在任何给定版本的代码中哪些存在哪些不存在。

由于您可能在私有配置中加载了密钥,因此您绝对不希望在任何前端代码中加载私有配置。虽然严格来说,将前端代码库与后端代码库完全分离可能更理想,但很多时候,PITA是一个足够大的障碍,阻止人们这样做,从而导致私有配置与公共配置。但是我做了两件事来防止在前端加载私有配置:

我有一个单元测试,确保我的前端包不包含我在私有配置中的一个密钥。 我将前端代码放在与后端代码不同的文件夹中,并且我有两个名为“config.js”的不同文件-一端一个。对于后端,config.js加载私有配置,对于前端,它加载公共配置。然后你总是只需要('config'),而不用担心它来自哪里。

最后一件事:您的配置应该通过一个完全独立于任何其他前端代码的文件加载到浏览器中。如果捆绑前端代码,公共配置应该作为一个完全独立的包构建。否则,你的配置就不再是真正的配置了——它只是你代码的一部分。配置需要能够在不同的机器上有所不同。