How do you configure environment specific configuration of a nodejs app
1) Using Config module
The
Install in your app directory, and edit the default config file.
$ npm install config
$ mkdir config
$ vi config/default.json
{
// Customer module configs
"Customer":
"dbConfig":
"host": "localhost"
"port": 5984
"dbName": "customers"
"credit":
"initialLimit": 100
// Set low for development
"initialDays": 1
}
Edit config overrides for production deployment:
$ vi config/production.json
{
}
Use configs in your code:
const config = ;
//...
const dbConfig = config;
db;
if config
const detail = config;
//...
}
config.get()
will throw an exception for undefined keys to help catch typos and missing values. Use config.has()
to test if a configuration value is defined.
Start your app server:
$ export NODE_ENV=production
$ node my-app.js
Running in this configuration, the
2) Using custom-env moduleport
and dbName
elements of dbConfig
will come from the default.json
file, and the host
element will come from the production.json
override file.Installation
npm install custom-env
Usage
Place this at the top of your application
require('custom-env').env()
This by default loads configuration from the
.env
file and assumes the app is in development enviroment mode.
Create a
.env
file in your app's root directory and add the environment variables each on new line:APP_ENV=dev
DB_HOST=localhost
DB_USER=root
DB_PASS=root
Simple! The
process.env
is now loaded with the environment variables above.Example
console.log(process.env.APP_ENV)
console.log(process.env.DB_HOST)
console.log(process.env.DB_USER)
console.log(process.env.DB_PASS)
Expected Output
dev
localhost
root
root
If you want to load from a particular environment, use:
// This loads configuration from staging environment
require('custom-env').env('staging')
Create a
.env.staging
file in your app's root directory and add the environment variables each on new line:APP_ENV=staging
DB_HOST=localhost
DB_USER=root
DB_PASS=root
The
process.env
is now loaded with the environment variables above. Try it out:NODE_ENV=staging node index.js
Example
console.log(process.env.APP_ENV)
console.log(process.env.DB_HOST)
console.log(process.env.DB_USER)
console.log(process.env.DB_PASS)
Expected Output
staging
localhost
root
root
Loading from the current environment
You can load configuration from the current environment with custom-env, just pass first argument of the
env()
method as true
(note: this must be a type Boolean type true
) and that's all:// This Loads the configuration dynamically from to the current enviroment
// Defaults to _dev_ if the environment was set
require('custom-env').env(true)
The env()
method
The
env()
method holds two (2) optional arguments envname
, path
which defaults to devand current working directory respectively. If you wish to set a different path rather than the current working directory, pass your path as the second argument of the env()
method.
Comments
Post a Comment