node.js 在sails.js 中创建配置变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18267706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:19:52  来源:igfitidea点击:

Create config variables in sails.js?

node.jsexpresssails.js

提问by user2688473

I'm converting an app of mine from Express to sails.js- is there a way I can do something like this in Sails?

我正在将我的一个应用程序从 Express 转换为sails.js- 有没有办法在 Sails 中做这样的事情?

From my app.jsfile in Express:

从我app.js在 Express 中的文件:

var globals = {
    name: 'projectName',
    author: 'authorName'
};

app.get('/', function (req, res) {
    globals.page_title = 'Home';
    res.render('index', globals);
});

This let me access those variables on every view without having to hardcode them into the template. Not sure how/where to do it in Sails though.

这让我可以在每个视图上访问这些变量,而无需将它们硬编码到模板中。不知道在 Sails 中如何/在哪里做。

回答by ataman

You can create your own config file in config/folder. For example config/myconf.jswith your config variables:

您可以在config/文件夹中创建自己的配置文件。例如config/myconf.js使用您的配置变量:

module.exports.myconf = {
    name: 'projectName',
    author: 'authorName',

    anyobject: {
      bar: "foo"
    }
};

and then access these variables from any view via global sailsvariable.

然后通过全局sails变量从任何视图访问这些变量。

In a view:

在一个观点:

<!-- views/foo/bar.ejs -->
<%= sails.config.myconf.name %>
<%= sails.config.myconf.author %>

In a service

服务中

// api/services/FooService.js
module.exports = {

  /**
   * Some function that does stuff.
   *
   * @param  {[type]}   options [description]
   * @param  {Function} cb      [description]
   */
  lookupDumbledore: function(options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails` is not available out here
// (it doesn't exist yet)
console.log(sails);  // ==> undefined

In a model:

在模型中:

// api/models/Foo.js
module.exports = {
  attributes: {
    // ...
  },

  someModelMethod: function (options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails is not available out here
// (doesn't exist yet)

In a controller:

在控制器中:

Note: This works the same way in policies.

注意:这在策略中的工作方式相同。

// api/controllers/FooController.js
module.exports = {
  index: function (req, res) {

    // `sails` is available in here

    return res.json({
      name: sails.config.myconf.name
    });
  }
};

// `sails is not available out here
// (doesn't exist yet)

回答by Matt Payne

I just made a service which delivers a value:

我刚刚制作了一项提供价值的服务:

maxLimbs: function(){
        var maxLimbs = 15;
        return maxLimbs;
    }