在sails.js中处理生产/开发/测试配置

时间:2014-02-14 22:14:29

标签: sails.js

有谁知道在帆中处理prod / dev / test配置切换的最佳方法?我真的很喜欢actionhero.js如何基于NODE_ENV的内容自动加载config / environment / {env} .js但是我没有看到在sails中做类似事情的内置方法。我注意到sails会在服务器引导期间加载config /中的任何文件,所以我现在的hacky解决方案是设置以下内容:

config/
|-- local.js
|-- environment/
|---- production.js
|---- staging.js
|---- development.js
|---- testing.js

然后在每个{env} .js文件中,我只是像这样扩展配置:

if (process.env.NODE_ENV === 'production') {
  // Enter any environment specific config changes
  config.db = {
    db_host: foo,
    db_port: bar
  }
  config.otherThing = {
    somevar: 'someval'
  }

3 个答案:

答案 0 :(得分:15)

由于Sails 0.10-rc6已得到改进,您现在可以在env中添加config子文件夹来更改不同环境的设置。

因此,您只需添加可覆盖所有必要设置的文件/config/env/development.js/config/env/production.js

有关详细信息,请参阅https://github.com/balderdashy/sails/pull/1638

更改端口和数据库适配器的示例,例如对于production中的production.js环境:

module.exports = {
  port: 80
};

module.exports.models = {

  // Your app's default connection.
  // i.e. the name of one of your app's connections (see `config/connections.js`)
  //
  // (defaults to localDiskDb)
  connection: 'someMongodbServer'
};

答案 1 :(得分:12)

只需转到config / env / production.js&手动设置端口和环境

并使用NODE_ENV

适用于Windows set NODE_ENV=production

对于MAC / Linux使用export NODE_ENV=production

OR

sails lift --prod

enter image description here

答案 2 :(得分:6)

我这样做是为了让config/local.js需要额外的配置文件,具体取决于process.env.NODE_ENV

config/local.js

var fs = require('fs'),
   lodash = require('lodash');

// config.local.js
module.exports = (function () {
  var defaults = {
    env: process.env.NODE_ENV || 'development',
    port: process.env.PORT || 1337,
    config: {
      paths: {
        environments: __dirname + '/environments'
      }
    }
  };

  var envConfigPath = defaults.config.paths.environments + '/' + defaults.env + '.js';
  var environment = {};

  if (fs.existsSync(envConfigPath)) {
    var environment = require(envConfigPath);
    logger.info('Loaded environment config for ' + defaults.env + '.');
  } else {
    logger.warn('Environment config for ' + defaults.env +' not found.');
  }
  return _.merge(defaults, environment);
}());

.gitignore

# config.local.js
config/environments

这会给您:

  • env
  • 中定义基于config/environments/{env}.js的任何配置的覆盖
  • sails.config{env}保留所有特定于环境的配置,就像您的解决方案一样
  • 好的声明{env}个文件
  • 有关缺少{env}个文件的警告