【问题标题】:reference sails config outside module.exports在 module.exports 之外参考 Sails 配置
【发布时间】:2016-01-24 16:47:03
【问题描述】:

如何在 module.exports 之外使用sails.config?我正在尝试将sails.config 变量传递给另一个对象,如下所示;

var foo = new Foo(sails.config.myconf.myVar);

module.exports {
  bar : function(){
    // Use foo here
    foo.blah();
  }
};

(在 Create config variables in sails.js? 的评论中也提出了同样的问题,请参阅 @jreptak 评论)

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    每个 Sails 配置文件都是一个模块,如果你想使用它,你只需要导入它。

    这里是导入sails.config.connections模块的Sails连接的示例。
    注意require中模块的路径,必须是相对的。

    var connections = require('../../config/connections');
    

    【讨论】:

      【解决方案2】:

      这在 Sails v0.9 中是不可能的。但是,现在可以在 Sails v0.10 及更高版本中实现这一点。

      这里是github上的具体问题:https://github.com/balderdashy/sails/issues/1672

      所以现在你可以这样做:

      //MyService.js
      var client = new Client(sails.config.client);
      module.exports = {
         myMethod: function(callback){
            client.doSomething();
         }
      }
      

      如果您无法使用 Sails v0.9,我建议您遵循 github 问题中指定的解决方法:

       //MyService.js
      var client;
      module.exports = function(){
        client = client || new Client(sails.config.client);
        return {
          myMethod: function(){
            client.doSomething();
          }
        }
      }
      

      可以这样使用:

      //SomeController.js
      module.exports = {
         list: function(req,res){
            MyService().myMethod();
         }
      }
      

      【讨论】:

        【解决方案3】:

        你不能这样做,如果你想访问 sails.config 参数,你必须创建一个自定义挂钩 http://sailsjs.org/documentation/concepts/extending-sails/hooks 并在其中发挥你的“魔法”

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-29
          • 1970-01-01
          • 1970-01-01
          • 2018-01-25
          • 2018-06-15
          • 1970-01-01
          • 2013-04-13
          • 2012-09-19
          相关资源
          最近更新 更多