Express Web Application Development
上QQ阅读APP看书,第一时间看更新

Using a configuration file

We actually don't need to use an .ini file for configuring our apps, as shown in a previous example. The purpose of the example was just to show you how to use a Node module, not the recommended practice.

As a side effect of how require() works, Node supports JSON-based configuration files by default. Create a file with a JSON object describing the configurations, save it with a .json extension, and then load it in the app file using require().

Note

It is important to ensure that the file extension is .json and the JSON object confirms to the JSON specification, or else it will throw an error.

Here is an example of a JSON-based config file:

{
  "development": {
    "db_host": "localhost",
    "db_user": "root",
    "db_pass": "root"
  },

  "production": {
    "db_host": "192.168.1.9",
    "db_user": "myappdb",
    "db_pass": "!p4ssw0rd#"
  }
}

This is how you would load it:

var config = require('./config.json')[app.get('env')];

Now the environment-specific configuration details will be available on the config object. Assuming your app is running on production, the following would be the result of using the configuration file:

console.log(config.db_host); // 192.168.1.9
console.log(config.db_user); // myappdb
console.log(config.db_pass); // !p4ssw0rd#

A configuration file is not mandatory for an Express app, but it helps in making it modular and maintainable.