diff --git a/lib/nconf/stores/env.js b/lib/nconf/stores/env.js index 47ac3bc..0b33db6 100644 --- a/lib/nconf/stores/env.js +++ b/lib/nconf/stores/env.js @@ -24,6 +24,7 @@ var Env = exports.Env = function (options) { this.whitelist = options.whitelist || []; this.separator = options.separator || ''; this.lowerCase = options.lowerCase || false; + this.parseJson = options.parseJson || false; if (({}).toString.call(options.match) === '[object RegExp]' && typeof options !== 'string') { @@ -78,11 +79,31 @@ Env.prototype.loadEnv = function () { return !self.whitelist.length || self.whitelist.indexOf(key) !== -1 } }).forEach(function (key) { + + var val = env[key]; + + if (self.parseJson) { + try { + var ret = JSON.parse(val); + + // apply JSON parsing only if its non-primitive types: JSON Object or Array + // avoid breaking backward-compatibility + if (typeof ret !== 'number' && + typeof ret !== 'string' && + typeof ret !== 'boolean') { + val = ret; + } + + } catch (ignore) { + //ignore + } + } + if (self.separator) { - self.set(common.key.apply(common, key.split(self.separator)), env[key]); + self.set(common.key.apply(common, key.split(self.separator)), val); } else { - self.set(key, env[key]); + self.set(key, val); } }); diff --git a/test/complete-test.js b/test/complete-test.js index 7476fcf..c2df651 100644 --- a/test/complete-test.js +++ b/test/complete-test.js @@ -22,6 +22,8 @@ process.env.FOO = 'bar'; process.env.BAR = 'zalgo'; process.env.NODE_ENV = 'debug'; process.env.FOOBAR = 'should not load'; +process.env.json_array = JSON.stringify(['foo', 'bar', 'baz']); +process.env.json_obj = JSON.stringify({foo: 'bar', baz: 'foo'}); vows.describe('nconf/multiple-stores').addBatch({ "When using the nconf with multiple providers": { @@ -156,4 +158,40 @@ vows.describe('nconf/multiple-stores').addBatch({ nconf.remove('env'); } } +}).addBatch({ + // Threw this in it's own batch to make sure it's run separately from the + // sync check + "When using env with parseJson:true": { + topic: function () { + var that = this; + helpers.cp(complete, completeTest, function () { + nconf.env({ parseJson: true }); + that.callback(); + }); + }, + "env vars": { + "JSON keys properly parsed": function () { + Object.keys(process.env).forEach(function (key) { + var val = process.env[key]; + + try { + var ret = JSON.parse(val); + + // apply JSON parsing only if its non-primitive types: JSON Object or Array + // avoid breaking backward-compatibility + if (typeof ret !== 'number' && + typeof ret !== 'string' && + typeof ret !== 'boolean') { + val = ret; + } + } catch (err) {} + + assert.deepEqual(nconf.get(key), val); + }); + } + }, + teardown: function () { + nconf.remove('env'); + } + } }).export(module); \ No newline at end of file