Json config file in Node application

Here you learn how to read JSON config file in node js application, like any other type of application, in node js we also can have config file, which typically contain information related to database configuration, email configuration etc.

In node application, we can create .json config file and can store information in json format.

We need to install nconf module in our application.

 npm install nconf

Read JSON File in Node Application

with the help of nconf module, we can load config file into local instance and then read from there.

As you can see in example below, we can specify the file name like file: 'appconfig.json'.

//nconf.argv().env();

nconf.file({ file: 'appconfig.json' });

Now let's look at how the config file will look like, you can give any name to config file then save the file with .json extension.

appconfig.json
{
  "dbInfo":
    {
        "host":"localhost",
        "database":"mydatabaseName",
        "username":"myusername",
        "password":"pass123",
        "port":"0001"
    },
    "emailInfo":{
        "username":"myemail@gmail.com",
        "password":"myemailpasword",
        "smtp":"smtp.yahoo.com"
    }
}

Now to read any key from configuration file in node application, use nconf.get('sectionName:keyName'), Remember if there is no section in your json file structure, where you have stored any value with direct key, then you do not need to specify the section name, just key name will work fine. like nconf.get('keyName')

    console.log(nconf.get('dbInfo:database'));
 
Node Config File
Learn Node application development, free node js framework tutorial with examples.
Node examples | Join JavaScript Course