1

My question relates to an old answer given on this question but with a small modification.

I'll try an keep it simple as possible.

Suppose my folder structure is the following

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

Relevant files contains

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

This might be a silly question but how can I use the application setting i.e. app.get('env') within config.js?

Mikey
  • 6,728
  • 4
  • 22
  • 45

1 Answers1

2

One way you could do it would be to parse the process.env.NODE_ENV || 'production' in your config file and then reference it when you instantiate your app. Another thing to consider is using process.env.NODE_ENV || 'development' instead so that devs have to explicitly say they are in a production environment. You don't want to accidentally use production

const env = require('env.json')
module.exports = env[process.env.NODE_ENV || 'production']
jmarthernandez
  • 104
  • 1
  • 8
  • 2
    I was about to also comment on dev as default and not prod ;-) – Scott Stensland Aug 11 '17 at 16:45
  • 1
    So basically not to use application setting in the config file. My end goal was to have one place where I would do `process.env.NODE_ENV || 'production'`. Though, according to the [documentation](http://expressjs.com/en/api.html#app.set), the default value for `app.set()` is `process.env.NODE_ENV || 'development'`. Since it's better to use `development`, I guess it works out. Thanks. – Mikey Aug 11 '17 at 19:03