【问题标题】:Setting up environment-specific configurations using app.get('env')使用 app.get('env') 设置特定于环境的配置
【发布时间】:2018-01-20 06:00:56
【问题描述】:

我的问题与an old answer given on this question 相关,但稍作修改。

我会尽量保持简单。

假设我的文件夹结构如下

|-- controllers
    |-- File.js
    |-- and many more...
|-- routes.js
|-- app.js
|-- config.js
|-- env.json (same as one in the old answer)

相关文件包含

app.js

const routes = require('./routes');

app.set('env', process.env.NODE_ENV || 'production'); // set the environment
app.use('/', routes);

routes.js

const FileController = require('./controllers/File');

let router = require('express').Router();

router.get('/files', FileController.getFiles);

// ...

module.exports = router;

controllers/File.js

const config = require('../config');

exports.getFiles = (req, res, next) => {
    // I would like to use the environment-specific (that was set in app.js) config here
    console.log(config.facebook_app_id);
};

// ...

config.js

const env = require('env.json');

/*exports.config = function() {
    var node_env = process.env.NODE_ENV || 'development';
    return env[node_env];
};*/

module.exports = env[app.get('env')]; // this would cause an error as app is not defined

这可能是一个愚蠢的问题,但我如何在config.js 中使用应用程序设置,即app.get('env')?

【问题讨论】:

    标签: node.js environment-variables application-settings


    【解决方案1】:

    一种方法是解析配置文件中的process.env.NODE_ENV || 'production',然后在实例化应用程序时引用它。要考虑的另一件事是改用process.env.NODE_ENV || 'development',这样开发人员必须明确表示他们处于生产环境中。你不想不小心使用生产

    const env = require('env.json')
    module.exports = env[process.env.NODE_ENV || 'production']
    

    【讨论】:

    • 我还打算评论 dev 作为默认而不是 prod ;-)
    • 所以基本上不要在配置文件中使用应用程序设置。我的最终目标是拥有一个可以做process.env.NODE_ENV || 'production' 的地方。不过,根据documentation,app.set() 的默认值为process.env.NODE_ENV || 'development'。由于使用development 更好,我想它会成功。谢谢。
    猜你喜欢
    • 2016-02-17
    • 2017-12-08
    • 2011-06-25
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2016-03-17
    相关资源
    最近更新 更多