节点。js设置用于每个用户的特定环境配置

时间:2021-06-18 02:48:50

I am using node.js + express.js + everyauth.js. I have moved all my everyauth logic into a module file

我用节点。js +表达。js + everyauth.js。我已经将所有的一切逻辑移动到一个模块文件中

var login = require('./lib/everyauthLogin');

inside this I load my oAuth config file with the key/secret combinations:

在这个文件中,我用密钥/秘密组合加载我的oAuth配置文件:

var conf = require('./conf');
.....
twitter: {
    consumerKey: 'ABC', 
    consumerSecret: '123'
}

These codes are different for different environments - development / staging / production as the callbacks are to different urls.

这些代码对于不同的环境是不同的——开发/登台/生产,因为回调是针对不同的url。

Qu. How do I set these in the environmental config to filter through all modules or can I pass the path directly into the module?

我如何在环境配置中设置这些来过滤所有模块,或者我是否可以将路径直接传递到模块中?

Set in env:

env设置:

app.configure('development', function(){
  app.set('configPath', './confLocal');
});

app.configure('production', function(){
  app.set('configPath', './confProduction');
});

var conf = require(app.get('configPath'));

Pass in

通过

app.configure('production', function(){
  var login = require('./lib/everyauthLogin', {configPath: './confProduction'});
});

? hope that makes sense

吗?希望是有意义的

7 个解决方案

#1


179  

My solution,

我的解决方案,

load the app using

加载应用程序使用

NODE_ENV=production node app.js

Then setup config.js as a function rather than an object

然后设置配置。js是函数而不是对象

module.exports = function(){
    switch(process.env.NODE_ENV){
        case 'development':
            return {dev setting};

        case 'production':
            return {prod settings};

        default:
            return {error or other settings};
    }
};

Then as per Jans solution load the file and create a new instance which we could pass in a value if needed, in this case process.env.NODE_ENV is global so not needed.

然后,根据Jans解决方案,加载文件并创建一个新实例,如果需要,我们可以将该实例传入一个值,在本例中为process.env。NODE_ENV是全局的,所以不需要。

var Config = require('./conf'),
    conf = new Config();

Then we can access the config object properties exactly as before

然后我们可以像以前一样访问配置对象属性

conf.twitter.consumerKey

#2


50  

You could also have a JSON file with NODE_ENV as the top level. IMO, this is a better way to express configuration settings (as opposed to using a script that returns settings).

您还可以使用NODE_ENV作为顶层的JSON文件。在我看来,这是一种更好的表达配置设置的方式(而不是使用返回设置的脚本)。

var config = require('./env.json')[process.env.NODE_ENV || 'development'];

Example for env.json:

env.json的例子:

{
    "development": {
        "MONGO_URI": "mongodb://localhost/test",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    },
    "production": {
        "MONGO_URI": "mongodb://localhost/production",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    }
}

#3


28  

A very useful solution is use the config module.

一个非常有用的解决方案是使用配置模块。

after install the module:

后安装的模块:

$ npm install config

You could create a default.json configuration file. (you could use JSON or JS object using extension .json5 )

您可以创建一个默认值。json配置文件。(可以使用扩展名为.json5的JSON或JS对象)

For example

例如

$ vi config/default.json

{
  "name": "My App Name",
  "configPath": "/my/default/path",
  "port": 3000
}

This default configuration could be override by environment config file or a local config file for a local develop environment:

此默认配置可以由环境配置文件或本地配置文件覆盖,用于本地开发环境:

production.json could be:

生产。json可以:

{
  "configPath": "/my/production/path",
  "port": 8080
}

development.json could be:

发展。json可以:

{
  "configPath": "/my/development/path",
  "port": 8081
}

In your local PC you could have a local.json that override all environment, or you could have a specific local configuration as local-production.json or local-development.json.

在您的本地PC中,您可以有一个本地的。可以覆盖所有环境的json,也可以将特定的本地配置作为本地生产。json或local-development.json。

The full list of load order.

装载顺序的完整列表。

Inside your App

在你的应用程序

In your app you only need to require config and the needed attribute.

在您的应用程序中,您只需要配置和所需的属性。

var conf = require('config'); // it loads the right file
var login = require('./lib/everyauthLogin', {configPath: conf.get('configPath'));

Load the App

加载应用程序

load the app using:

加载应用程序的使用:

NODE_ENV=production node app.js

or setting the correct environment with forever or pm2

或者使用forever或pm2设置正确的环境

Forever:

永远:

NODE_ENV=production forever [flags] start app.js [app_flags]

PM2 (via shell):

PM2(通过shell):

export NODE_ENV=staging
pm2 start app.js

PM2 (via .json):

PM2(通过. json):

process.json

process.json

{
   "apps" : [{
    "name": "My App",
    "script": "worker.js",
    "env": {
      "NODE_ENV": "development",
    },
    "env_production" : {
       "NODE_ENV": "production"
    }
  }]
}

And then

然后

$ pm2 start process.json --env production

This solution is very clean and it makes easy set different config files for Production/Staging/Development environment and for local setting too.

这个解决方案非常干净,它可以方便地为生产/登台/开发环境和本地设置设置设置不同的配置文件。

#4


5  

The way we do this is by passing an argument in when starting the app with the environment. For instance:

我们这样做的方法是在启动应用程序时传入一个参数。例如:

node app.js -c dev

In app.js we then load dev.js as our configuration file. You can parse these options with optparse-js.

在app.js中,我们将dev.js作为配置文件加载。您可以使用optparse-js解析这些选项。

Now you have some core modules that are depending on this config file. When you write them as such:

现在您有了一些依赖于这个配置文件的核心模块。当你这样写的时候:

var Workspace = module.exports = function(config) {
    if (config) {
         // do something;
    }
}

(function () {
    this.methodOnWorkspace = function () {

    };
}).call(Workspace.prototype);

And you can call it then in app.js like:

你可以在app.js中调用它:

var Workspace = require("workspace");
this.workspace = new Workspace(config);

#5


5  

In brief

This kind of a setup is simple and elegant :

这种设置简单而优雅:

env.json

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

app.js

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

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js

在生产模式下运行:$ NODE_ENV=生产节点app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

这个解决方案来自:http://himanshu.gilani.info/blog/2012/09/26/bootstrap -a-node-dot-js-app-for dev-slash-prod-environment/,请查看详细信息。

#6


4  

An elegant way is to use .env file to locally override production settings. No need for command line switches. No need for all those commas and brackets in a config.json file. See my answer here

一种优雅的方法是使用.env文件在本地覆盖生产设置。不需要命令行开关。不需要配置中所有的逗号和括号。json文件。看到我的答案

Example: on my machine the .env file is this:

例:在我的机器上。env文件是这样的:

NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls

My local .env overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage or production NODE_ENV=prod.

我的本地.env覆盖任何环境变量。但是在登台或生产服务器上(可能在heroku.com上),环境变量被预先设置为stage NODE_ENV=stage或production NODE_ENV=prod。

#7


3  

How about doing this in a much more elegant way with nodejs-config module.

用nodejs-config模块以一种更优雅的方式来做这个怎么样?

This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.

此模块可以根据计算机的名称设置配置环境。之后,当您请求配置时,您将获得特定于环境的值。

For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:

例如,假设您有两台名为pc1和pc2的开发机器和一台名为pc3的生产机器。当您在pc1或pc2中请求代码中的配置值时,您必须获得“开发”环境配置,在pc3中必须获得“生产”环境配置。可以这样实现:

  1. Create a base configuration file in the config directory, lets say "app.json" and add required configurations to it.
  2. 在config目录中创建一个基本配置文件,让我们写入“app.json”,并添加所需的配置。
  3. Now simply create folders within the config directory that matches your environment name, in this case "development" and "production".
  4. 现在只需在配置目录中创建与环境名匹配的文件夹,在本例中为“开发”和“生产”。
  5. Next, create the configuration files you wish to override and specify the options for each environment at the environment directories(Notice that you do not have to specify every option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.).
  6. 接下来,创建希望覆盖的配置文件,并为环境目录中的每个环境指定选项(请注意,您不必指定基配置文件中的每个选项,而只需指定希望覆盖的选项。环境配置文件将在基本文件上“级联”。

Now create new config instance with following syntax.

现在使用以下语法创建新的配置实例。

var config = require('nodejs-config')(
   __dirname,  // an absolute path to your applications 'config' directory
   {
      development: ["pc1", "pc2"],
      production: ["pc3"],

   }
);

Now you can get any configuration value without worrying about the environment like this:

现在您可以得到任何配置值,而不必担心这样的环境:

config.get('app').configurationKey;

#1


179  

My solution,

我的解决方案,

load the app using

加载应用程序使用

NODE_ENV=production node app.js

Then setup config.js as a function rather than an object

然后设置配置。js是函数而不是对象

module.exports = function(){
    switch(process.env.NODE_ENV){
        case 'development':
            return {dev setting};

        case 'production':
            return {prod settings};

        default:
            return {error or other settings};
    }
};

Then as per Jans solution load the file and create a new instance which we could pass in a value if needed, in this case process.env.NODE_ENV is global so not needed.

然后,根据Jans解决方案,加载文件并创建一个新实例,如果需要,我们可以将该实例传入一个值,在本例中为process.env。NODE_ENV是全局的,所以不需要。

var Config = require('./conf'),
    conf = new Config();

Then we can access the config object properties exactly as before

然后我们可以像以前一样访问配置对象属性

conf.twitter.consumerKey

#2


50  

You could also have a JSON file with NODE_ENV as the top level. IMO, this is a better way to express configuration settings (as opposed to using a script that returns settings).

您还可以使用NODE_ENV作为顶层的JSON文件。在我看来,这是一种更好的表达配置设置的方式(而不是使用返回设置的脚本)。

var config = require('./env.json')[process.env.NODE_ENV || 'development'];

Example for env.json:

env.json的例子:

{
    "development": {
        "MONGO_URI": "mongodb://localhost/test",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    },
    "production": {
        "MONGO_URI": "mongodb://localhost/production",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    }
}

#3


28  

A very useful solution is use the config module.

一个非常有用的解决方案是使用配置模块。

after install the module:

后安装的模块:

$ npm install config

You could create a default.json configuration file. (you could use JSON or JS object using extension .json5 )

您可以创建一个默认值。json配置文件。(可以使用扩展名为.json5的JSON或JS对象)

For example

例如

$ vi config/default.json

{
  "name": "My App Name",
  "configPath": "/my/default/path",
  "port": 3000
}

This default configuration could be override by environment config file or a local config file for a local develop environment:

此默认配置可以由环境配置文件或本地配置文件覆盖,用于本地开发环境:

production.json could be:

生产。json可以:

{
  "configPath": "/my/production/path",
  "port": 8080
}

development.json could be:

发展。json可以:

{
  "configPath": "/my/development/path",
  "port": 8081
}

In your local PC you could have a local.json that override all environment, or you could have a specific local configuration as local-production.json or local-development.json.

在您的本地PC中,您可以有一个本地的。可以覆盖所有环境的json,也可以将特定的本地配置作为本地生产。json或local-development.json。

The full list of load order.

装载顺序的完整列表。

Inside your App

在你的应用程序

In your app you only need to require config and the needed attribute.

在您的应用程序中,您只需要配置和所需的属性。

var conf = require('config'); // it loads the right file
var login = require('./lib/everyauthLogin', {configPath: conf.get('configPath'));

Load the App

加载应用程序

load the app using:

加载应用程序的使用:

NODE_ENV=production node app.js

or setting the correct environment with forever or pm2

或者使用forever或pm2设置正确的环境

Forever:

永远:

NODE_ENV=production forever [flags] start app.js [app_flags]

PM2 (via shell):

PM2(通过shell):

export NODE_ENV=staging
pm2 start app.js

PM2 (via .json):

PM2(通过. json):

process.json

process.json

{
   "apps" : [{
    "name": "My App",
    "script": "worker.js",
    "env": {
      "NODE_ENV": "development",
    },
    "env_production" : {
       "NODE_ENV": "production"
    }
  }]
}

And then

然后

$ pm2 start process.json --env production

This solution is very clean and it makes easy set different config files for Production/Staging/Development environment and for local setting too.

这个解决方案非常干净,它可以方便地为生产/登台/开发环境和本地设置设置设置不同的配置文件。

#4


5  

The way we do this is by passing an argument in when starting the app with the environment. For instance:

我们这样做的方法是在启动应用程序时传入一个参数。例如:

node app.js -c dev

In app.js we then load dev.js as our configuration file. You can parse these options with optparse-js.

在app.js中,我们将dev.js作为配置文件加载。您可以使用optparse-js解析这些选项。

Now you have some core modules that are depending on this config file. When you write them as such:

现在您有了一些依赖于这个配置文件的核心模块。当你这样写的时候:

var Workspace = module.exports = function(config) {
    if (config) {
         // do something;
    }
}

(function () {
    this.methodOnWorkspace = function () {

    };
}).call(Workspace.prototype);

And you can call it then in app.js like:

你可以在app.js中调用它:

var Workspace = require("workspace");
this.workspace = new Workspace(config);

#5


5  

In brief

This kind of a setup is simple and elegant :

这种设置简单而优雅:

env.json

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

app.js

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

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js

在生产模式下运行:$ NODE_ENV=生产节点app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

这个解决方案来自:http://himanshu.gilani.info/blog/2012/09/26/bootstrap -a-node-dot-js-app-for dev-slash-prod-environment/,请查看详细信息。

#6


4  

An elegant way is to use .env file to locally override production settings. No need for command line switches. No need for all those commas and brackets in a config.json file. See my answer here

一种优雅的方法是使用.env文件在本地覆盖生产设置。不需要命令行开关。不需要配置中所有的逗号和括号。json文件。看到我的答案

Example: on my machine the .env file is this:

例:在我的机器上。env文件是这样的:

NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls

My local .env overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage or production NODE_ENV=prod.

我的本地.env覆盖任何环境变量。但是在登台或生产服务器上(可能在heroku.com上),环境变量被预先设置为stage NODE_ENV=stage或production NODE_ENV=prod。

#7


3  

How about doing this in a much more elegant way with nodejs-config module.

用nodejs-config模块以一种更优雅的方式来做这个怎么样?

This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.

此模块可以根据计算机的名称设置配置环境。之后,当您请求配置时,您将获得特定于环境的值。

For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:

例如,假设您有两台名为pc1和pc2的开发机器和一台名为pc3的生产机器。当您在pc1或pc2中请求代码中的配置值时,您必须获得“开发”环境配置,在pc3中必须获得“生产”环境配置。可以这样实现:

  1. Create a base configuration file in the config directory, lets say "app.json" and add required configurations to it.
  2. 在config目录中创建一个基本配置文件,让我们写入“app.json”,并添加所需的配置。
  3. Now simply create folders within the config directory that matches your environment name, in this case "development" and "production".
  4. 现在只需在配置目录中创建与环境名匹配的文件夹,在本例中为“开发”和“生产”。
  5. Next, create the configuration files you wish to override and specify the options for each environment at the environment directories(Notice that you do not have to specify every option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.).
  6. 接下来,创建希望覆盖的配置文件,并为环境目录中的每个环境指定选项(请注意,您不必指定基配置文件中的每个选项,而只需指定希望覆盖的选项。环境配置文件将在基本文件上“级联”。

Now create new config instance with following syntax.

现在使用以下语法创建新的配置实例。

var config = require('nodejs-config')(
   __dirname,  // an absolute path to your applications 'config' directory
   {
      development: ["pc1", "pc2"],
      production: ["pc3"],

   }
);

Now you can get any configuration value without worrying about the environment like this:

现在您可以得到任何配置值,而不必担心这样的环境:

config.get('app').configurationKey;