Search code examples
node.jsjsonconfigurationrequire

Make required json available in other modules


I am writing an application that has configuration parameters in a json file. Something like this:

// config.json
{
  "httpServer": {
    "port": 3000
  },
  "module1": {
    "setting1": "value1",
    "setting2": "value2"
  },
  "module2": {
    "setting1": "value1",
    "setting2": "value2"
  }
}
// index.js
const config = require("./config")
const func1 = require("./module1")
const func2 = require("./module2")

// code here

// module1.js

const config = require("./config")

// use config and define functions

module.exports = {

function: function

}

// module2.js

const config = require("./config")

// use config and define functions

module.exports = {

function: function

}

The problem is that I am requiring this file in every module which makes my code unmaintainable since I need to update every require statement if the filename changes. I am pretty sure that this is not the "correct" way of doing this. Can I require the configuration file once when the program starts and then reference to it in other modules? Or should I pass the configuration file as a command line argument and then use process.argv array when requiring the file? What is the best way of handling situations like these?


Solution

  • use dotenv package npm install dotenv --save,

    create a config file

    //config.env
    NODE_ENV=development
    IP=127.0.0.1
    PORT=3000
    

    load the config file

    //index.js
    const dotenv = require('dotenv');
    dotenv.config({ path: './config.env' })
    

    use it where ever you want

    //module1
    console.log('IP: ',process.env.IP)