DEV Community

Razielini
Razielini

Posted on

Using node-config

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
Enter fullscreen mode Exit fullscreen mode

Create files

Later, create the config files.

    $ mkdir config
    $ vi config/default.json
Enter fullscreen mode Exit fullscreen mode
    {
         // Customer module configs
         "Customer":  {
             "dbConfig":  {
             "host":  "localhost",
             "port":  5984,
             "dbName":  "customers"
             },
             "credit":  {
                 "initialLimit":  100,
                 // Set low for development
                 "initialDays":  1
             }
         }
     }
Enter fullscreen mode Exit fullscreen mode

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');
         //...
     }
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Can validate if exist a property before to use

config.has('optionalFeature.detail')
Enter fullscreen mode Exit fullscreen mode

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)