Sometimes we need to create and use configuration files. One of the ways to create and use configurations is by using a config module. The first step is to install it using the following command:

npm install config

When we do this we have to create a directory with a name “config“(directory name/path can be changed using env variables, this is the default name). After that, we have to create a file in which we will store data. I use a .json file(File type can be different). The name of the file is “default“. In this module, you can use a chain of the file and their value is taken by priority. For file extensions and priority, you can read more here.

Example use you can find here:

var config = require("config");

console.log(config.has("test_var"));
console.log(config.get("var1"));
console.log(config.get("var2"));
console.log(config.get("var3"));
console.log(config.get("var4"));
console.log(config.var1);
console.log(config.var2[0]);
console.log(config.var3.a);

The first row includes the project. There are two functions “has” and “get“. You can use the first if the variable exists and second to get the value of variable/property you need.

The configuration .json file:

{
    "var1":"123",
    "var2":[1,2,3],
    "var3":{
        "a":"test",
        "b":"test2"
    },
    "var4":123
}

The result of the script you can see here:

The result from script execution

Note: Additional information for supported file types and order of loading config files you can find here

Was this article helpful?