Node.js:如何为 prod 和 staging 设置不同的变量

2022-01-24 00:00:00 node.js express javascript coffeescript

I'm using Express and I need to use different credentials for each server (staging and production).

I could setup the variables in the server.coffee file but then I'd need to access those variables in different files.

server.coffee:

app.configure 'production', () ->
 app.use express.errorHandler()

What's the solution? Setup the variables and then export them?

解决方案

./config.js

var development = {
  appAddress : '127.0.0.1:3000',
  socketPort : 4000,
  socketHost : '127.0.0.1',
  env : global.process.env.NODE_ENV || 'development'
};

var production = {
  appAddress : 'someDomain.com',
  socketPort : 4000,
  socketHost : '8.8.8.8',
  env : global.process.env.NODE_ENV || 'production'
};

exports.Config = global.process.env.NODE_ENV === 'production' ? production : development;

./app.js

var cfg = require('./config').Config;

if (cfg.something) { // switch on environment
  // your logic
}

相关文章