Skip to content

Instantly share code, notes, and snippets.

@rnkoaa
Last active January 3, 2016 05:39
Show Gist options
  • Save rnkoaa/8416858 to your computer and use it in GitHub Desktop.
Save rnkoaa/8416858 to your computer and use it in GitHub Desktop.
A process in which we can run node apps with different environment settings which are declared in a different file. This helps in scalability and deployment.

How to run node in an environment aware setting.

  1. Create a config folder /config
  2. 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
	    }
	}  
  1. Create a properties file in the config folder /config/properties.js
  2. 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];
	};
  1. 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);
	});
  1. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment