arnaucube
arnaucube/raspberryGPIOhtmlserverPublic Self-hosted repository
raspberryGPIOhtmlserver/node_modules/options/lib/options.js
node_modules/options/lib/options.jsRaw
 1/*!
 2 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
 3 * MIT Licensed
 4 */
 5
 6var fs = require('fs');
 7
 8function 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]; },
15      configurable: false,
16      enumerable: true
17    });
18  });
19  this.reset = function() {
20    Object.keys(defaults).forEach(function(key) {
21      internalValues[key] = defaults[key];
22    });
23    return this;
24  };
25  this.merge = function(options, required) {
26    options = options || {};
27    if (Object.prototype.toString.call(required) === '[object Array]') {
28      var missing = [];
29      for (var i = 0, l = required.length; i < l; ++i) {
30        var key = required[i];
31        if (!(key in options)) {
32          missing.push(key);
33        }
34      }
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');
40        }
41        else throw new Error('option ' + missing[0] + ' must be defined');
42      }
43    }
44    Object.keys(options).forEach(function(key) {
45      if (key in internalValues) {
46        internalValues[key] = options[key];
47      }
48    });
49    return this;
50  };
51  this.copy = function(keys) {
52    var obj = {};
53    Object.keys(defaults).forEach(function(key) {
54      if (keys.indexOf(key) !== -1) {
55        obj[key] = values[key];
56      }
57    });
58    return obj;
59  };
60  this.read = function(filename, cb) {
61    if (typeof cb == 'function') {
62      var self = this;
63      fs.readFile(filename, function(error, data) {
64        if (error) return cb(error);
65        var conf = JSON.parse(data);
66        self.merge(conf);
67        cb();
68      });
69    }
70    else {
71      var conf = JSON.parse(fs.readFileSync(filename));
72      this.merge(conf);
73    }
74    return this;
75  };
76  this.isDefined = function(key) {
77    return typeof values[key] != 'undefined';
78  };
79  this.isDefinedAndNonNull = function(key) {
80    return typeof values[key] != 'undefined' && values[key] !== null;
81  };
82  Object.freeze(values);
83  Object.freeze(this);
84}
85
86module.exports = Options;