Node.js Loading environment properties from a "property file"


Example

  • Install properties reader:
npm install properties-reader --save
  • Create a directory env to store your properties files:
mkdir env
  • Create environments.js:
process.argv.forEach(function (val, index, array) {
    var arg = val.split("=");
    if (arg.length > 0) {
        if (arg[0] === 'env') {
            var env = require('./env/' + arg[1] + '.properties');
            module.exports = env;
        }
    }
});
  • Sample development.properties properties file:
# Dev properties
[main]
# Application port to run the node server
app.port=8080

[database]
# Database connection to mysql
mysql.host=localhost
mysql.port=2500
...
  • Sample usage of the loaded properties:
var enviorment = require('./environments');
var PropertiesReader = require('properties-reader');
var properties = new PropertiesReader(enviorment);
   
var someVal = properties.get('main.app.port');
  • Starting the express server
npm start env=development

or

npm start env=production