How to Use nconf for Environment Configuration at Node.js
This blog shows how to use nconf for Node.js environment configuration. Environment config is needed in any coding language, for instance, the database endpoint for each of the environments, your development, and production should be different.
Install the nconf
Now, use nconf is very easy, first add to your solution's dependency package.
npm install nconf --save
Use the nconf
You can write a helper class like following to use nconf. First, you import the package to your file, load json file, then return the nconf.
const nconf = require('nconf'); nconf.file('env.json'); exports.config = nconf;
This JSON file will be your App's environment configuration, you can put all your configuration dependencies to this JSON file. Later, each of your environments just updates this JSON file to match that environment's config.
{ "AWS": { "region": "us-west-1" }, "Port": 3000 }
Load the Config Value
You can simply load the config value by following code.
// load port config.get("Port") // load nest object config.get('AWS:region')
You can use other Node.js config packages, e.g. dotenv, but in my opinion, the nconf is much easier to use. The config file is much easy to define, just a JSON format.