2 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
6 var fs = require('fs');
8 function Options(defaults) {
9 var internalValues = {};
10 var values = this.value = {};
11 Object.keys(defaults).forEach(function(key) {
12 internalValues[key] = defaults[key];
13 Object.defineProperty(values, key, {
14 get: function() { return internalValues[key]; },
19 this.reset = function() {
20 Object.keys(defaults).forEach(function(key) {
21 internalValues[key] = defaults[key];
25 this.merge = function(options, required) {
26 options = options || {};
27 if (Object.prototype.toString.call(required) === '[object Array]') {
29 for (var i = 0, l = required.length; i < l; ++i) {
30 var key = required[i];
31 if (!(key in options)) {
35 if (missing.length > 0) {
36 if (missing.length > 1) {
37 throw new Error('options ' +
38 missing.slice(0, missing.length - 1).join(', ') + ' and ' +
39 missing[missing.length - 1] + ' must be defined');
41 else throw new Error('option ' + missing[0] + ' must be defined');
44 Object.keys(options).forEach(function(key) {
45 if (key in internalValues) {
46 internalValues[key] = options[key];
51 this.copy = function(keys) {
53 Object.keys(defaults).forEach(function(key) {
54 if (keys.indexOf(key) !== -1) {
55 obj[key] = values[key];
60 this.read = function(filename, cb) {
61 if (typeof cb == 'function') {
63 fs.readFile(filename, function(error, data) {
64 if (error) return cb(error);
65 var conf = JSON.parse(data);
71 var conf = JSON.parse(fs.readFileSync(filename));
76 this.isDefined = function(key) {
77 return typeof values[key] != 'undefined';
79 this.isDefinedAndNonNull = function(key) {
80 return typeof values[key] != 'undefined' && values[key] !== null;
82 Object.freeze(values);
86 module.exports = Options;