Accessing config variables from other config files

核能气质少年 提交于 2020-01-01 08:38:17

问题


I am having problems using in a config file a config var set in another config file. E.g.

// file - config/local.js
module.exports = {
  mongo_db : {
    username : 'TheUsername',
    password : 'ThePassword',
    database : 'TheDatabase'
  }
}

// file - config/connections.js
module.exports.connections = {
  mongo_db: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    user: sails.config.mongo_db.username,
    password: sails.config.mongo_db.password,
    database: sails.config.mongo_db.database
  },
}

When I 'sails lift', I get the following error:

user: sails.config.mongo_db.username,
      ^
ReferenceError: sails is not defined

I can access the config variables in other places - e.g, this works:

// file - config/bootstrap.js
module.exports.bootstrap = function(cb) {
  console.log('Dumping config: ', sails.config);
  cb();
}

This dumps all the config settings to the console - I can even see the config settings for mongo_db in there!

I so confuse.


回答1:


You can't access sails inside of config files, since Sails config is still being loaded when those files are processed! In bootstrap.js, you can access the config inside the bootstrap function, since that function gets called after Sails is loaded, but not above the function.

In any case, config/local.js gets merged on top of all the other config files, so you can get what you want this way:

// file - config/local.js
module.exports = {
  connections: {
    mongo_db : {
      username : 'TheUsername',
      password : 'ThePassword',
      database : 'TheDatabase'
    }
  }
}

// file - config/connections.js
module.exports.connections = {
  mongo_db: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017
  },
}

If you really need to access one config file from another you can always use require, but it's not recommended. Since Sails merges config files together based on several factors (including the current environment), it's possible you'd be reading some invalid options. Best to do things the intended way: use config/env/* files for environment-specific settings (e.g. config/env/production.js), config/local.js for settings specific to a single system (like your computer) and the rest of the files for shared settings.



来源:https://stackoverflow.com/questions/25622955/accessing-config-variables-from-other-config-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!