miconfig — Configuration loader for Node.js, browsers & Deno.
$ npm install miconfig --save
In miconfig, a configuration has a NODE_ENV
value associated.
You can load them for anywhere, e.g., from a folder called config
:
.
├── index.js
└── config
├── default.js
├── production.js
├── staging.js
└── test.js
Just call miconfig passing these configuration:
const loadConfig = require('miconfig')
const FILES = [
'default',
NODE_ENV === 'development' ? undefined : NODE_ENV
].filter(Boolean)
const environment = FILES.reduce(
(acc, key) => ({
...acc,
[key]: require(`./config/${key}`)
}),
{}
)
const config = loadConfig(environment)
In case you want to use a different file format (like YAML), you’ve to parser them before be loaded:
const loadConfig = require('miconfig')
const yaml = require('js-yaml')
const fs = require('fs')
const fromYaml = filepath => yaml.safeLoad(fs.readFileSync(filepath, 'utf8'))
const FILES = [
'default',
NODE_ENV === 'development' ? undefined : NODE_ENV
].filter(Boolean)
const environment = FILES.reduce(
(acc, key) => ({
...acc,
[key]: fromYaml(`./config/${key}.yml`)
}),
{}
)
const config = loadConfig(environment)
The configuration default
will always be loaded, being possible overwrite these defaults values by the current NODE_ENV
configuration.
In case you want to use a different source of truth rather than NODE_ENV
, you can pass it as second argument:
const loadConfig = require('miconfig')
const config = loadConfig({
default: require('./config/default'),
production: require('./config/default')
}, process.env.APP_ENV)
After miconfig loads your configuration, you can safely access to any value
// read a value, don't care if it's empty
const database = config.get('database')
// read a value, use a default if empty
const database = config.get('database', 'localhost')
// read a value, throw an error if it doesn't exist
const database = config.require('database')
// check if a value exists
if (config.has('feature.prerender')) {
console.log('prerender is enabled')
}
Additionally, you can retrieve more than one value at one time with destructuring assignment:
// read multiple values, don't care if it's empty
const { timezone, database } = config
// read multiple values, throw an error if it doesn't exist
const { timezone, database } = config.required
Author: Kikobeats
Source Code: https://github.com/Kikobeats/miconfig
#deno #node #nodejs #javascript