8 Commits
Author SHA1 Message Date
harish2704 d7c5fd2b00 * Added verbose messages
* Updated docs
V 0.1.4
2017-07-30 00:45:48 +05:30
harish2704 4a10b8149b Fix: better way to set sub keys in the configuration 2017-07-26 13:43:26 +05:30
harish2704 58a7593f7e * Feature: parse env variable value with JSON.parse so that, we can set set config variables with proper type 2017-07-06 15:59:04 +05:30
harish2704 23b899df60 * Rm unwanted dependency
* Fix docs
2017-06-08 18:52:35 +05:30
harish2704 38fd5d04aa * Update Readme
* Update examples
* Version bump
2017-06-08 16:34:52 +05:30
harish2704 c8aae33840 Added deep merge instead of Object.assign 2017-06-08 16:34:20 +05:30
harish2704 106a9d7cbb * Fix config dir lookup procedure
* Check in current directory and also throw error if config dir not found.
2017-05-25 20:26:32 +05:30
harish2704 ea1f06b940 Version 2016-12-07 14:33:05 +05:30
6 changed files with 116 additions and 21 deletions
+1
View File
@@ -0,0 +1 @@
example
+37 -12
View File
@@ -38,43 +38,68 @@ hari@hari-VirtualBox:~app$ node xyz.js
``` ```
#### Override using NODE_ENV #### Read additional config based on NODE_ENV variable.
values from config/production overides the default one If we specify NODE_ENV=xyz then, config/xyz.js will overide the values from default.js. **Overriding is a deep merge**
```bash ```bash
hari@hari-VirtualBox:~app$ env NODE_ENV=production node xyz.js hari@hari-VirtualBox:~app$ env NODE_ENV=production node xyz.js
{ port: 5000 } { port: 4000 }
``` ```
#### Override using Environtment Variables. #### Set any configuration variable using Environtment variable.
Default prefix is `TC_` By setting an Environtment variable '<Prefix><key>=<value>', we can set config[key] as value.
** First we will try to parse value as json. It it is failed value will be treated as string **
** If a values if parsable as JSON object, then it will be deep merged with default configuration **
Default prefix is `TC_` ( Can be changed by setting TC_PREFIX` env variable `)
For eg:
* `TC_port` will set config.port
* `TC_a.b.c` will set config.a.b.c
* `TC_a='{"a":{"b":{"c": 123546 }}}'` will also set `config.a.b.c`
* `TC_port=8000` will set `{ port: 8000 }` By default, number will parsed as json number.
* `TC_port='"8000"'` will set `{ port: '8000' }` ( **now port is a string** because double quoted value will be parsed as string in json )
TC_port will set config.port
TC_a.b.c will set config.a.b.c
```bash ```bash
hari@hari-VirtualBox:~app$ env NODE_ENV=production TC_db.mysql.user=root node xyz.js hari@hari-VirtualBox:~app$ env NODE_ENV=production TC_db.mysql.user=root node xyz.js
{ port: 5000, db: { mysql: { user: 'root' } } } { port: 4000, db: { mysql: { user: 'root' } } }
``` ```
#### Override using Environtment Variables. Custom Prefix ##### Use custom env prefix.
Prefix can be changed using Environtment variable
default prefix can be changed using Environtment variable by setting `TC_PREFIX` Environtment variable
```bash ```bash
export TC_PREFIX=MYAPP_ export TC_PREFIX=MYAPP_
export MYAPP_PORT=8080 export MYAPP_port=8080
hari@hari-VirtualBox:~app$ env MYAPP_db.mysql.user=root node xyz.js hari@hari-VirtualBox:~app$ env MYAPP_db.mysql.user=root node xyz.js
{ port: 8080, db: { mysql: { user: 'root' } } } { port: 8080, db: { mysql: { user: 'root' } } }
``` ```
#### use custom config directory #### use custom config directory
config directory can be changed using Environtment variable config directory can be changed using Environtment variable by setting `CONFIG_DIR` Environtment variable
```bash ```bash
hari@hari-VirtualBox:~app$ env CONFIG_DIR=../config TC_PREFIX=MYAPP_ NODE_ENV=production MYAPP_db.mysql.user=root node xyz.js hari@hari-VirtualBox:~app$ env CONFIG_DIR=../config TC_PREFIX=MYAPP_ NODE_ENV=production MYAPP_db.mysql.user=root node xyz.js
{ dir: '../config', db: { mysql: { user: 'root' } } } { dir: '../config', db: { mysql: { user: 'root' } } }
``` ```
#### printing debug messages
set `DEBUG` environment variable to `tconfig`
```bash
export DEBUG=tconfig
# OR
export DEBUG='*'
```
#### Config directory search path
* Directory pointed by `CONFIG_DIR` environment variable
* < directory or main script >/config
* < current working directory >/config
+5 -1
View File
@@ -1,3 +1,7 @@
{ {
"port":3000 "port":3000,
"pool":{
"min":2,
"max":10
}
} }
+1 -1
View File
@@ -1,2 +1,2 @@
console.log( require('tconfig')); console.log( require('../../'));
+68 -5
View File
@@ -1,21 +1,80 @@
var path = require('path'); var path = require('path');
var configDIR = process.env.CONFIG_DIR || path.resolve( path.join( require.main.paths[0], '..', 'config' ) ); var fs = require('fs');
var configDir;
var env = ( process.env.NODE_ENV || 'development' ).toLowerCase(); var env = ( process.env.NODE_ENV || 'development' ).toLowerCase();
var envPrefix = process.env.TC_PREFIX || 'TC_'; var envPrefix = process.env.TC_PREFIX || 'TC_';
var envRegex = new RegExp( '^' + envPrefix + '(.*)' ); var envRegex = new RegExp( '^' + envPrefix + '(.*)' );
var finalConfig = {}; var finalConfig = {};
var configDirLookupPath = [
path.join( process.env.PWD, 'config' )
];
var beVerbose = process.env.DEBUG && 'tconfig'.match( process.env.DEBUG.replace( /\*/g, '.*' ) );
var log = beVerbose ? console.log.bind( console, 'tconfig:: ' ) : function(){};
if( require.main ){
configDirLookupPath.unshift( path.resolve( path.join( require.main.paths[0], '..', 'config' ) ) );
}
if( process.env.CONFIG_DIR ){
configDirLookupPath.unshift( process.env.CONFIG_DIR );
}
for (var i = 0, l = configDirLookupPath.length; i < l; i ++) {
var v = configDirLookupPath[i];
if( fs.existsSync(v) ){
configDir = v;
log( 'Found config dir: ' + configDir );
break;
}
}
if( !configDir ){
throw Error(
'Config directory not found.\n Look up at following locations failed.\n---\n** ' +
configDirLookupPath.join('\n** ') + '\n---\n' +
'\n Please set CONFIG_DIR env variable');
}
function processSpecial( str ){
var out;
try {
out = JSON.parse(str);
} catch (e) {
out = str;
}
return out;
}
function loadConfig( name ){ function loadConfig( name ){
log('Loading config ' + name );
var out = {}; var out = {};
try{ try{
out = require( configDIR + '/' + name ); out = require( configDir + '/' + name );
} catch(e){ } catch(e){
log( 'Error loading config ' + name, e );
out = {}; out = {};
} }
return out; return out;
} }
function assignDeep( src, dest1, dest2 ){
var key, val;
for( key in dest1 ){
val = dest1[ key ];
if( val.constructor.name === 'Object' ){
if( ( !src.hasOwnProperty(key) ) || ( src[ key ].constructor.name !== 'Object' ) ){
src[ key ] = {};
}
assignDeep( src[ key ], val );
} else {
src[ key ] = val;
}
}
if( dest2 ){
assignDeep( src, dest2 );
}
return src;
}
/* Implementation of lodash.set function */ /* Implementation of lodash.set function */
function setProp( object, keys, val ){ function setProp( object, keys, val ){
keys = Array.isArray( keys )? keys : keys.split('.'); keys = Array.isArray( keys )? keys : keys.split('.');
@@ -23,17 +82,21 @@ function setProp( object, keys, val ){
object[keys[0]] = object[keys[0]] || {}; object[keys[0]] = object[keys[0]] || {};
return setProp( object[keys[0]], keys.slice(1), val ); return setProp( object[keys[0]], keys.slice(1), val );
} }
if( val instanceof Object ){
return assignDeep( object[keys[0]], val );
}
object[keys[0]] = val; object[keys[0]] = val;
} }
Object.assign( finalConfig, loadConfig('default'), loadConfig( env ) ); assignDeep( finalConfig, loadConfig('default'), loadConfig( env ) );
var envList = Object.keys( process.env ).filter( function(v){ Object.keys( process.env ).filter( function(v){
var match = v.match( envRegex ); var match = v.match( envRegex );
if( match ){ if( match ){
setProp( finalConfig, match[1].toLowerCase(), process.env[v] ); setProp( finalConfig, match[1], processSpecial( process.env[v] ) );
} }
}); });
log('Final config ', JSON.stringify(finalConfig, null, 2 ) );
module.exports = finalConfig; module.exports = finalConfig;
+4 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "tconfig", "name": "tconfig",
"version": "0.0.1", "version": "0.1.4",
"description": "A simple transparent config file loader for Nodejs applications. any config field can be overriden using environmen variables", "description": "A simple transparent config file loader for Nodejs applications. any config field can be overriden using environmen variables",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
@@ -20,5 +20,7 @@
"bugs": { "bugs": {
"url": "https://github.com/harish2704/tconfig/issues" "url": "https://github.com/harish2704/tconfig/issues"
}, },
"homepage": "https://github.com/harish2704/tconfig#readme" "homepage": "https://github.com/harish2704/tconfig#readme",
"dependencies": {
}
} }