Tutorial about node-config.
Hi! I'm Razielini, and I want to share a package for node I discover some weeks ago, which has been very useful for me.
The package is node-config, created by Loren West.
This package takes the setup level to your next level and is very easy to use and understand.
Installation
The installation is very simple as usual.
npm install config
Create files
Later, create the config files.
$ 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
}
}
}
Use config in your code
const config = require('config');
//...
const dbConfig = config.get('Customer.dbConfig');
db.connect(dbConfig, ...);
if (config.has('optionalFeature.detail')) {
const detail = config.get('optionalFeature.detail');
//...
}
This is where you can start to notice a difference, the package gives you a method to extract information from the config file as if were any object.
config.get('Customer.dbConfig')
Can validate if exist a property before to use
config.has('optionalFeature.detail')
And has many other functions like set variables en execution time, override your config with other config files, or even import automatically the values of the variables in a .env file.
You can check the Wiki page with the full documentation of this package.
Top comments (0)