Skip to content

Instantly share code, notes, and snippets.

@psenger
Created February 16, 2023 01:07
Show Gist options
  • Select an option

  • Save psenger/04a14babff645a2a4556a21b3dfee631 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/04a14babff645a2a4556a21b3dfee631 to your computer and use it in GitHub Desktop.
[Simple test to illustrate how `config.js` works with regards to defaulting and overriding] #JavaScript #config.js

Simple test to illustrate how config.js works with regards to defaulting and overriding.

It appears that it works simaliar to Object.assign({},{})

e.g.

const fs = require('fs')
const path = require('path')
const config = Object.assign(
    JSON.parse(fs.readFileSync(path.join(__dirname,'config','default.json'),'utf-8')),
    JSON.parse(fs.readFileSync(path.join(__dirname,'config',`${process.env.NODE_ENV}.json`),'utf-8')))

Config layout

./config
├── default.json
├── development.json
├── production.json
└── test.json

./config/default.json

{
  "overrideable": "default.json",
  "defaultValue": "default.json"
}

./config/development.json

{
  "overrideable": "development.json"
}

./config/test.json

{
  "overrideable": "test.json"
}

./config/production.json

{
  "overrideable": "production.json"
}

Outcome

const config = require('config')

console.log(
    'NODE_ENV=',
    process.env.NODE_ENV
);
console.log(
    'config.overrideable = ',
    config.has('overrideable') ? config.get('overrideable') : 'undefined'
);
console.log(
    'config.defaultValue = ',
    config.has('defaultValue') ? config.get('defaultValue') : 'undefined'
);

undefined

export NODE_ENV= && node index.js 
NODE_ENV= 
config.overrideable =  development.json
config.defaultValue =  default.json

development

export NODE_ENV=development && node index.js
NODE_ENV= development
config.overrideable =  development.json
config.defaultValue =  default.json

test

export NODE_ENV=test && node index.js
NODE_ENV= test
config.overrideable =  test.json
config.defaultValue =  default.json

production

export NODE_ENV=production && node index.js

NODE_ENV= production
config.overrideable =  production.json
config.defaultValue =  default.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment