Node.js setting up environment specific configs to

2019-01-05 07:34发布

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

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

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

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.

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:

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条回答
冷血范
2楼-- · 2019-01-05 08:04

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.

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:

var Workspace = require("workspace");
this.workspace = new Workspace(config);
查看更多
登录 后发表回答