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
?
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']