简体   繁体   中英

How to load config json as environment variable nodejs

I am a newbie to node js. I have different configs for different environments viz dev, prod etc. Currently while creating my app package I copy .json to config.json and then export config.json as config variable (global) and use it throughout the app.

config = require(__dirname + '/config/config'); (config.httpProxy && config.httpProxy.enabled);

I want to load specific env.json as part of environment variable (for dev dev.json's all keys are exported as global variable in app) instead of copying it into app's config.json, so that same app can be used in different env. How to do that.

PS: for application packaging support and dependency management I use gulp and npm.

Please help.

I suggest you use this module called config it handles all your env config files. https://www.npmjs.com/package/config

Just make a folder named config and makes files in it as :

1. development.json
2. qa.json
3. production.json

While starting server provide relevant environment as others mentioned. Then you can use any property mentioned in your config files.

you can name your files like this:

config.development.json
config.production.json
config.test.json

Then load files as:

config = require(__dirname + '/config/config.' + process.env.NODE_ENV);

where process.env.NODE_ENV value can be development/production/test

you have to start your application as

NODE_ENV=development node app.js

for this to work.

If you are running your project from your script then set NODE_ENV into your package.json file.

    {
       ...
      "scripts": {
        "nodemon:server": "NODE_ENV=dev NODE_PATH=. nodemon --exec \"babel-node --stage 1\" server.js",
         "prod:server": "NODE_ENV=prod NODE_PATH=. nodemon --exec \"babel-node --stage 1\" server.js"

      },
      "author": "'Shubham Batra'",
      "license": "MIT",
      ....
    }
"prod:server": "**NODE_ENV=prod** NODE_PATH=. nodemon --exec \"babel-node --stage 1\" server.js"

than use in config,js file eg

if (process.env.NODE_ENV === 'test' ) {
    url = 'http://abc:3000';
    dbUrl= 'xyz';
    password = '***';

} else if (process.env.NODE_ENV === 'prod') {
    url = 'http://def:3000';
   ...
}
export default {

  conf: {
   url,
    dbUrl,
   ...
   }
}

after that, you can import this config file anywhere in your project and use conf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM