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

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

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


当前回答

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

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

支持前端。如果前端不能使用该配置有什么意义? 支持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

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

其他回答

有点晚了(只有10年),但我使用的config.js结构如下:

const env = process.env.NODE_ENV || 'development';

var config_temp = {
    default:{
        port: 3000,
        mysql_host: "localhost",
        logging_level: 5,
        secret_api_key: process.env.SECRET_API_KEY
    },
    development: {
        logging_level: 10
    },
    production: {
        port: 3001,
        mysql_host: "not-localhost"
    }
};
var config = {
    ...config_temp.default, 
    ...config_temp[env]
}
module.exports = config;

然后我加载配置:

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

这样:

env变量的读取包含在config.js文件中,因此我可以避免这种丑陋的情况:NODE_ENV || 'development']。 config.js文件可以在代码的repo中上传,因为敏感变量继续由process.env处理。 如果default:{和custom_env:{中都包含同一个元素,则只保留第二个元素。 没有专用文件夹和多个文件(像在配置中)

现在,在使用数据库时,最简单的方法是完全不处理配置文件,因为部署环境更容易设置,只需使用单个环境变量(例如,将其称为DB_CONNECTION),并根据需要向其传递任何额外的配置数据。

配置数据举例:

const config = {
    userIds: [1, 2, 3],
    serviceLimit: 100,
    // etc., configuration data of any complexity    
};
// or you can read it from a config file

创建一个连接字符串,包含数据库驱动程序不关心的额外参数:

import {ConnectionString} from 'connection-string';

const cs = new ConnectionString('postgres://localhost@dbname', {
    user: 'user-name',
    password: 'my-password',
    params: {
        config
    }  ​
});

然后我们可以生成结果字符串存储在环境中:

cs.toString();
//=>postgres://localhost:my-password@dbname?config=%7B%22userIds%22%3A%5B1%2C2%2C3%5D%2C%22serviceLimit%22%3A100%7D

所以你把它存储在你的环境中,比如说DB_CONNECTION,在客户端进程中你可以通过process.env.DB_CONNECTION读取它:

const cs = new ConnectionString(process.env.DB_CONNECTION);

const config = JSON.parse(cs.params?.config); // parse extra configuration
//=> { userIds: [ 1, 2, 3 ], serviceLimit: 100 }

通过这种方式,您将在单个环境变量中同时拥有连接和所需的所有额外配置,而不需要打乱配置文件。

我用一个包装。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中,并为我的生产服务器添加了遥控器。

你们使用npm来启动你的脚本(env等)吗?

如果你使用.env文件,你可以将它们包含在package.json中 并使用NPM来源/启动它们。

例子:

{
  "name": "server",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node test.js",
    "start-dev": "source dev.env; node test.js",
    "start-prod": "source prod.env; node test.js"
  },
  "dependencies": {
    "mysql": "*"
  }
}

然后运行NPM脚本:

$ npm start-dev

描述在这里https://gist.github.com/ericelliott/4152984 这都要归功于埃里克·埃利奥特

您可以将Konfig用于特定于环境的配置文件。它自动加载json或yaml配置文件,它有默认值和动态配置功能。

Konfig repo的一个例子:

File: config/app.json
----------------------------
{
    "default": {
        "port": 3000,
        "cache_assets": true,
        "secret_key": "7EHDWHD9W9UW9FBFB949394BWYFG8WE78F"
    },

    "development": {
        "cache_assets": false
    },

    "test": {
        "port": 3001
    },

    "staging": {
        "port": #{process.env.PORT},
        "secret_key": "3F8RRJR30UHERGUH8UERHGIUERHG3987GH8"
    },

    "production": {
        "port": #{process.env.PORT},
        "secret_key": "3F8RRJR30UHERGUH8UERHGIUERHG3987GH8"
    }
}

在发展:

> config.app.port
3000

在生产环境中,假设我们使用$ NODE_ENV=生产PORT=4567节点app.js启动应用程序

> config.app.port
4567

详情:https://github.com/vngrs/konfig