1

Based on this answer here https://stackoverflow.com/a/22524056/777700 I have set exactly the same configuration options, but it doesn't work.

My (partial) app.js file:

console.log('environment: '+process.env.NODE_ENV);

const config = require('./config/db.json')[process.env.NODE_ENV || "development"];

console.log(config);

My ./config/db.json file:

{
    "development":{
        "host":"localhost",
        "port":"3306",
        "username":"root",
        "password":"",
        "database":"dbname"
    },
    "production":{
        "host":"production-host",
        "port":"3306",
        "username":"user",
        "password":"pwd",
        "database":"dbname"
    }
}

Console.log outputs:

environment: development
undefined

and app crashes. Any idea why? File is there, if I remove the [...] part of require(), it does print out the db.json file, with it, it prints out undefined.

EDIT I tried to add console.log(typeof config) just after require() to see what I'm getting and I have noticed that if I require('./config/db.json')[process.env.NODE_ENV] I get undefined, but if I require('./config/db.json')["development"] I get back proper object.

Versions:

nodeJS 6.11.4
express 4.16.2
Kristjan O.
  • 814
  • 1
  • 9
  • 33

4 Answers4

1

After more debugging and searching online, I have finally found the solution. The problem is that I'm on Windows machine and I was using npm run dev command while my "dev" command looked like SET NODE_ENV=development && nodemon server.js.

Experienced eye will notice a space before &&, which added a space behind the variable development, so the variable I was comparing against was "development " and not "development" as I was thinking.

So, the original answer from other question does work and it does load proper config!

Kristjan O.
  • 814
  • 1
  • 9
  • 33
0

You should export configuration as a variable:

const config = {
    "development":{
        "host":"localhost",
        "port":"3306",
        "username":"root",
        "password":"",
        "database":"dbname"
    },
    "production":{
        "host":"production-host",
        "port":"3306",
        "username":"user",
        "password":"pwd",
        "database":"dbname"
    }
};
module.exports = config;

This way it will be found :)

Michele Bontorno
  • 1,157
  • 2
  • 13
  • 27
0

If you want to do it via JSON:

const fs = require('fs')
let localConfig

try {
    localConfig = JSON.parse((fs.readFileSync('./config/db.json', 'utf-8'))
} catch (e) {
    console.log('Could not parse local config.')
    localConfig = false
}

module.exports = localConfig

You could then add logic for production, if there's no local configuration localConfig will return false and you can look for environment variables injected at that point.

Update:

I see that you're giving the production config yourself, in that case you can just access the key you need based on the environment. Just import localConfig and use the keys you need.

cinnaroll45
  • 2,661
  • 7
  • 24
  • 41
0

Its better to use dotenv package for this

npm i dotenv

Step 1: In package.json add this

"scripts": {
    "start": "nodemon app.js",
    "dev": "NODE_ENV=dev nodemon app.js"
    "prod": "NODE_ENV=prod nodemon app.js"
  },

Step 2: Add .env.prod and .env.dev files

.env.dev

PORT=7200
# Set your database/API connection information here
DB_URI=localhost
DB_USERNAME=root
DB_PASSWORD=password
DB_DEFAULT=dbName

Step 3: Add this in config.js

const dotenv = require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });

const result = dotenv;
if (result.error) {
  throw result.error;
}
const { parsed: envs } = result;
// console.log(envs);
module.exports = envs;

Step 4: Use like this when needed

const {
  DB_URI, DB_USERNAME, DB_PASSWORD, DB_DEFAULT,
} = require('../config');

Now if u want for development, run

npm run dev

For prod, use

npm run prod
Gvs Akhil
  • 2,165
  • 2
  • 16
  • 33