You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.3 KiB

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