nconf-lite/lib/nconf/stores/env.js

83 lines
2 KiB
JavaScript
Raw Normal View History

/*
* env.js: Simple memory-based store for environment variables
*
2014-11-26 06:31:48 +00:00
* (C) 2011, Charlie Robbins and the Contributors.
*
*/
2012-04-14 19:28:55 +00:00
var util = require('util'),
common = require('../common'),
Memory = require('./memory').Memory;
2012-04-14 19:28:55 +00:00
//
// ### function Env (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Env nconf store, a simple abstraction
// around the Memory store that can read process environment variables.
//
var Env = exports.Env = function (options) {
Memory.call(this, options);
options = options || {};
this.type = 'env';
this.readOnly = true;
2012-06-21 08:05:52 +00:00
this.whitelist = options.whitelist || [];
this.separator = options.separator || '';
if (typeof options.match === 'function'
&& typeof options !== 'string') {
this.match = options.match;
}
if (options instanceof Array) {
2012-06-21 08:04:37 +00:00
this.whitelist = options;
}
if (typeof(options) === 'string') {
this.separator = options;
}
};
// Inherit from the Memory store
util.inherits(Env, Memory);
//
// ### function loadSync ()
// Loads the data passed in from `process.env` into this instance.
//
Env.prototype.loadSync = function () {
this.loadEnv();
return this.store;
};
//
// ### function loadEnv ()
// Loads the data passed in from `process.env` into this instance.
//
Env.prototype.loadEnv = function () {
var self = this;
2012-04-14 19:28:55 +00:00
this.readOnly = false;
Object.keys(process.env).filter(function (key) {
2014-11-26 06:06:44 +00:00
if (self.match && self.whitelist.length) {
2014-01-10 00:26:07 +00:00
return key.match(self.match) || self.whitelist.indexOf(key) !== -1
2014-11-26 06:06:44 +00:00
}
else if (self.match) {
return key.match(self.match);
2014-11-26 06:06:44 +00:00
}
else {
return !self.whitelist.length || self.whitelist.indexOf(key) !== -1
}
}).forEach(function (key) {
if (self.separator) {
self.set(common.key.apply(common, key.split(self.separator)), process.env[key]);
}
else {
self.set(key, process.env[key]);
}
});
2012-04-14 19:28:55 +00:00
this.readOnly = true;
return this.store;
};