How to run node in an environment aware setting.
- Create a config folder
/config
- Create an
/config/env.json
in the config folder which will hold the environmental properties for each environment. example
{
"development": {
"port": 3000
},
"production": {
"port": 80
}
}
- Create a properties file in the config folder
/config/properties.js
- In the properties file add the following:
var env = require('./env.json');
exports.config = function () {
var node_env = process.env.NODE_ENV || 'development';
return env[node_env];
};
- In the main node file example
app.js
file, we need to start using the config properties. example usage below.
var properties = require('./config/properties')
var config = properties.config();
var port = config.port;
app.set('port', process.env.PORT || port);
//we use the environment declared port here.
http.createServer(app).listen(port, function () {
console.log('Express server listening on port ' + port);
});
- Finally to run node with any of the environment properties, use any of the examples below:
NODE_ENV=production node app.js
NODE_ENV=production nodemon app.js
NODE_ENV=production pm2 start app.js