我使用的是node.js + express.js + everyauth.js。我已经将我所有的身份验证逻辑移动到一个模块文件中
var login = require('./lib/everyauthLogin');
在其中,我使用密钥/密钥组合加载了我的oAuth配置文件:
var conf = require('./conf');
.....
twitter: {
consumerKey: 'ABC',
consumerSecret: '123'
}
这些代码对于不同的环境-开发/暂存/生产环境是不同的,因为回调到不同的urls。
问题:如何在环境配置中设置这些参数来过滤所有模块,或者是否可以将路径直接传递到模块中?
环境中设置的:
app.configure('development', function(){
app.set('configPath', './confLocal');
});
app.configure('production', function(){
app.set('configPath', './confProduction');
});
var conf = require(app.get('configPath'));
中的传递
app.configure('production', function(){
var login = require('./lib/everyauthLogin', {configPath: './confProduction'});
});
?希望这是有意义的
发布于 2011-12-02 19:14:08
我的解决方案是
使用以下命令加载应用程序
NODE_ENV=production node app.js
然后将config.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};
}
};
然后根据Jans解决方案加载文件并创建一个新实例,如果需要,我们可以在值中传递该实例,在这种情况下,process.env.NODE_ENV
是全局的,因此不需要。
var Config = require('./conf'),
conf = new Config();
然后,我们就可以像以前一样访问配置对象属性
conf.twitter.consumerKey
发布于 2014-03-20 13:17:44
你也可以有一个NODE_ENV作为顶层的JSON文件。与使用返回设置的脚本相比,这是一种更好的表达配置设置的方法。
var config = require('./env.json')[process.env.NODE_ENV || 'development'];
Env.json示例:
{
"development": {
"MONGO_URI": "mongodb://localhost/test",
"MONGO_OPTIONS": { "db": { "safe": true } }
},
"production": {
"MONGO_URI": "mongodb://localhost/production",
"MONGO_OPTIONS": { "db": { "safe": true } }
}
}
发布于 2016-04-18 21:41:57
一个非常有用的解决方案是使用config module。
安装模块后:
$ npm install config
您可以创建一个default.json配置文件。(您可以通过扩展.json5使用JSON或JS对象)
例如
$ vi config/default.json
{
"name": "My App Name",
"configPath": "/my/default/path",
"port": 3000
}
此默认配置可由环境配置文件或本地开发环境配置文件覆盖:
production.json可以是:
{
"configPath": "/my/production/path",
"port": 8080
}
development.json可以是:
{
"configPath": "/my/development/path",
"port": 8081
}
在您本地PC中,您可以使用覆盖所有环境的local.json,也可以使用local-production.json或local-development.json.作为特定的本地配置
应用程序中的
在您的应用程序中,您只需要配置和所需的属性。
var conf = require('config'); // it loads the right file
var login = require('./lib/everyauthLogin', {configPath: conf.get('configPath'));
加载应用程序
使用以下命令加载应用程序:
NODE_ENV=production node app.js
或者使用forever或pm2设置正确的环境
永远的:
NODE_ENV=production forever [flags] start app.js [app_flags]
PM2 (通过shell):
export NODE_ENV=staging
pm2 start app.js
PM2 (通过.json):
process.json
{
"apps" : [{
"name": "My App",
"script": "worker.js",
"env": {
"NODE_ENV": "development",
},
"env_production" : {
"NODE_ENV": "production"
}
}]
}
然后
$ pm2 start process.json --env production
这个解决方案非常干净,它使得为生产/暂存/开发环境和本地设置设置不同的配置文件变得非常容易。
https://stackoverflow.com/questions/8332333
复制相似问题