-1

In my node app, I want to set production and development in my config.js file.

For that I have all most set all thing but I'm still missing something.

I want to get config data like database credential from config file based on my development mode. If I upload on live then app will use live cred. On other hand if I used local then it should be use local cred.

module.exports = function () {
    console.log("Process env is ::: ", process.env.NODE_ENV);
    if (process.env.NODE_ENV == 'production') {
        return {
            db : {
                host:'localhost',
                batabase:'dbname',
                username:'',
                password:''
            }
        }   
    } else {
        return {
            db : {
                host:'localhost',
                batabase:'dbname',
                username:'',
                password:''
            }
        }
    }
};

I have taken ref from this answer

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
khushboo
  • 715
  • 2
  • 11
  • 24

2 Answers2

1

Just try this way.

module.exports = (function () {
  process.env.NODE_ENV='development';
  if(process.env.NODE_ENV === 'production'){
       // Config data of Live
  }else{
       //Config data of Local
  }
})()

This works for me. :)

Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

process.env refers to the Environment Variables exists at the time you start you nodejs app . (it's part of the os)

When you deploy to cloud , usually it's handled for you already (process.env.NODE_ENV = production) . Some cloud providers even give you the option to control it via a GUI .

But for local environment , you can use .dotenv package . (https://github.com/motdotla/dotenv)

With this package you create a .env file at the top of your project ,

and just write down NODE_ENV = local/staging/production

Please note that you can always run in shell:

export NODE_ENV=production

(WATCH FOR WHITESPACES !) before you start you nodejs app which will also give you the effect of controlling process.env

Using the config files in other files, just by requiring it .

const config = require('path/to/config.js');

then config.data.host will be changed depend on the NODE_ENV

Mazki516
  • 997
  • 1
  • 10
  • 20