-
Notifications
You must be signed in to change notification settings - Fork 488
/
config.js
1684 lines (1490 loc) · 51.2 KB
/
config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// config.js (c) 2010-2015 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/node-config
// Dependencies
var Yaml = null, // External libraries are lazy-loaded
VisionmediaYaml = null, // only if these file types exist.
Coffee = null,
Iced = null,
CSON = null,
PPARSER = null,
JSON5 = null,
TOML = null,
HJSON = null,
deferConfig = require('../defer').deferConfig,
DeferredConfig = require('../defer').DeferredConfig,
Utils = require('util'),
Path = require('path'),
FileSystem = require('fs');
// Static members
var DEFAULT_CLONE_DEPTH = 20,
NODE_CONFIG, CONFIG_DIR, RUNTIME_JSON_FILENAME, NODE_ENV, APP_INSTANCE,
HOST, HOSTNAME, ALLOW_CONFIG_MUTATIONS,
env = {},
privateUtil = {},
deprecationWarnings = {},
configSources = [], // Configuration sources - array of {name, original, parsed}
checkMutability = true; // Check for mutability/immutability on first get
/**
* <p>Application Configurations</p>
*
* <p>
* The config module exports a singleton object representing all
* configurations for this application deployment.
* </p>
*
* <p>
* Application configurations are stored in files within the config directory
* of your application. The default configuration file is loaded, followed
* by files specific to the deployment type (development, testing, staging,
* production, etc.).
* </p>
*
* <p>
* For example, with the following config/default.yaml file:
* </p>
*
* <pre>
* ...
* customer:
* initialCredit: 500
* db:
* name: customer
* port: 5984
* ...
* </pre>
*
* <p>
* The following code loads the customer section into the CONFIG variable:
* <p>
*
* <pre>
* var CONFIG = require('config').customer;
* ...
* newCustomer.creditLimit = CONFIG.initialCredit;
* database.open(CONFIG.db.name, CONFIG.db.port);
* ...
* </pre>
*
* @module config
* @class Config
*/
/**
* <p>Get the configuration object.</p>
*
* <p>
* The configuration object is a shared singleton object within the application,
* attained by calling require('config').
* </p>
*
* <p>
* Usually you'll specify a CONFIG variable at the top of your .js file
* for file/module scope. If you want the root of the object, you can do this:
* </p>
* <pre>
* var CONFIG = require('config');
* </pre>
*
* <p>
* Sometimes you only care about a specific sub-object within the CONFIG
* object. In that case you could do this at the top of your file:
* </p>
* <pre>
* var CONFIG = require('config').customer;
* or
* var CUSTOMER_CONFIG = require('config').customer;
* </pre>
*
* <script type="text/javascript">
* document.getElementById("showProtected").style.display = "block";
* </script>
*
* @method constructor
* @return CONFIG {object} - The top level configuration object
*/
var Config = function() {
var t = this;
// Bind all utility functions to this
for (var fnName in util) {
util[fnName] = util[fnName].bind(t);
}
// Merge configurations into this
util.extendDeep(t, util.loadFileConfigs());
util.attachProtoDeep(t);
// Perform strictness checks and possibly throw an exception.
util.runStrictnessChecks(t);
};
/**
* Utilities are under the util namespace vs. at the top level
*/
var util = Config.prototype.util = {};
/**
* Underlying get mechanism
*
* @private
* @method getImpl
* @param object {object} - Object to get the property for
* @param property {string | array[string]} - The property name to get (as an array or '.' delimited string)
* @return value {mixed} - Property value, including undefined if not defined.
*/
var getImpl= function(object, property) {
var t = this,
elems = Array.isArray(property) ? property : property.split('.'),
name = elems[0],
value = object[name];
if (elems.length <= 1) {
return value;
}
if (typeof value !== 'object') {
return undefined;
}
return getImpl(value, elems.slice(1));
};
/**
* <p>Get a configuration value</p>
*
* <p>
* This will return the specified property value, throwing an exception if the
* configuration isn't defined. It is used to assure configurations are defined
* before being used, and to prevent typos.
* </p>
*
* @method get
* @param property {string} - The configuration property to get. Can include '.' sub-properties.
* @return value {mixed} - The property value
*/
Config.prototype.get = function(property) {
if(property === null || property === undefined){
throw new Error("Calling config.get with null or undefined argument");
}
var t = this,
value = getImpl(t, property);
// Produce an exception if the property doesn't exist
if (value === undefined) {
throw new Error('Configuration property "' + property + '" is not defined');
}
// Make configurations immutable after first get (unless disabled)
if (checkMutability) {
if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
util.makeImmutable(config);
}
checkMutability = false;
}
// Return the value
return value;
};
/**
* Test that a configuration parameter exists
*
* <pre>
* var config = require('config');
* if (config.has('customer.dbName')) {
* console.log('Customer database name: ' + config.customer.dbName);
* }
* </pre>
*
* @method has
* @param property {string} - The configuration property to test. Can include '.' sub-properties.
* @return isPresent {boolean} - True if the property is defined, false if not defined.
*/
Config.prototype.has = function(property) {
// While get() throws an exception for undefined input, has() is designed to test validity, so false is appropriate
if(property === null || property === undefined){
return false;
}
var t = this;
return (getImpl(t, property) !== undefined);
};
/**
* <p>Monitor a javascript property for runtime changes.</p>
*
* <p>
* This method was built for an earlier version of node-config that allowed
* configuration value mutations. Since version 1.0.0, node-config no longer
* allows configuration mutations, and is no longer used in node-config.
* </p>
*
* <p>
* It is deprecated, and will be removed in the next semver incompatible release 2.0.0.
* </p>
*
* @method watch
* @deprecated
* @param object {object} - The object to watch.
* @param property {string} - The property name to watch. Watch all object properties if null.
* @param handler {function(object, propertyName, priorValue, newValue)} - Handler called when a property change is detected.
* The handler is run along with other handlers registered for notification.
* If your handler changes the value of the property, that change is applied after all handlers have finished processing the current change.
* Then all handlers (including this one) will be called again with the newly changed value.
* @param depth {integer} (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes. Default 6.
* @return object {object} - The original object is returned - for chaining.
*/
util.watch = function(object, property, handler, depth) {
// Initialize
var t = this, o = object;
var allProperties = property ? [property] : Object.keys(o);
// Deprecation warning
if (!deprecationWarnings.watch) {
console.error('WARNING: config.' + fnName + '() is deprecated, and will not be supported in release 2.0.');
console.error('WARNING: See https://github.com/lorenwest/node-config/wiki/Future-Compatibility#upcoming-incompatibilities');
deprecationWarnings.watch = true;
}
// Depth detection
depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
if (depth < 0) {
return;
}
// Create hidden properties on the object
if (!o.__watchers)
util.makeHidden(o, '__watchers', {});
if (!o.__propertyValues)
util.makeHidden(o, '__propertyValues', {});
// Attach watchers to all requested properties
allProperties.forEach(function(prop){
// Setup the property for watching (first time only)
if (typeof(o.__propertyValues[prop]) === 'undefined') {
// Don't error re-defining the property if immutable
var descriptor = Object.getOwnPropertyDescriptor(o, prop);
if (descriptor && descriptor.writable === false)
return;
// Copy the value to the hidden field, and add the property to watchers
o.__propertyValues[prop] = [o[prop]];
o.__watchers[prop] = [];
// Attach the property watcher
Object.defineProperty(o, prop, {
enumerable : true,
get : function(){
// If more than 1 item is in the values array,
// then we're currently processing watchers.
if (o.__propertyValues[prop].length === 1)
// Current value
return o.__propertyValues[prop][0];
else
// [0] is prior value, [1] is new value being processed
return o.__propertyValues[prop][1];
},
set : function(newValue) {
// Return early if no change
var origValue = o[prop];
if (util.equalsDeep(origValue, newValue))
return;
// Remember the new value, and return if we're in another setter
o.__propertyValues[prop].push(newValue);
if (o.__propertyValues[prop].length > 2)
return;
// Call all watchers for each change requested
var numIterations = 0;
while (o.__propertyValues[prop].length > 1) {
// Detect recursion
if (++numIterations > 20) {
o.__propertyValues[prop] = [origValue];
throw new Error('Recursion detected while setting [' + prop + ']');
}
// Call each watcher for the current values
var oldValue = o.__propertyValues[prop][0];
newValue = o.__propertyValues[prop][1];
o.__watchers[prop].forEach(function(watcher) {
try {
watcher(o, prop, oldValue, newValue);
} catch (e) {
// Log an error and continue with subsequent watchers
console.error("Exception in object watcher for " + prop, e);
}
});
// Done processing this value
o.__propertyValues[prop].splice(0,1);
}
}
});
} // Done setting up the property for watching (first time)
// Add the watcher to the property
o.__watchers[prop].push(handler);
// Recurs if this is an object...
if (o[prop] && typeof(o[prop]) === 'object') {
util.watch(o[prop], null, handler, depth - 1);
}
}); // Done processing each property
// Return the original object - for chaining
return o;
};
/**
* <p>
* Set default configurations for a node.js module.
* </p>
*
* <p>
* This allows module developers to attach their configurations onto the
* default configuration object so they can be configured by the consumers
* of the module.
* </p>
*
* <p>Using the function within your module:</p>
* <pre>
* var CONFIG = require("config");
* CONFIG.util.setModuleDefaults("MyModule", {
* templateName: "t-50",
* colorScheme: "green"
* });
* <br>
* // Template name may be overridden by application config files
* console.log("Template: " + CONFIG.MyModule.templateName);
* </pre>
*
* <p>
* The above example results in a "MyModule" element of the configuration
* object, containing an object with the specified default values.
* </p>
*
* @method setModuleDefaults
* @param moduleName {string} - Name of your module.
* @param defaultProperties {object} - The default module configuration.
* @return moduleConfig {object} - The module level configuration object.
*/
util.setModuleDefaults = function (moduleName, defaultProperties) {
// Copy the properties into a new object
var t = this,
moduleConfig = util.cloneDeep(defaultProperties);
// Set module defaults into the first sources element
if (configSources.length === 0 || configSources[0].name !== 'Module Defaults') {
configSources.splice(0, 0, {
name: 'Module Defaults',
parsed: {}
});
}
configSources[0].parsed[moduleName] = {};
util.extendDeep(configSources[0].parsed[moduleName], defaultProperties);
// Create a top level config for this module if it doesn't exist
t[moduleName] = t[moduleName] || {};
// Extend local configurations into the module config
util.extendDeep(moduleConfig, t[moduleName]);
// Merge the extended configs without replacing the original
util.extendDeep(t[moduleName], moduleConfig);
// reset the mutability check for "config.get" method.
// we are not making t[moduleName] immutable immediately,
// since there might be more modifications before the first config.get
if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
checkMutability = true;
}
// Attach handlers & watchers onto the module config object
return util.attachProtoDeep(t[moduleName]);
};
/**
* <p>Make a configuration property hidden so it doesn't appear when enumerating
* elements of the object.</p>
*
* <p>
* The property still exists and can be read from and written to, but it won't
* show up in for ... in loops, Object.keys(), or JSON.stringify() type methods.
* </p>
*
* <p>
* If the property already exists, it will be made hidden. Otherwise it will
* be created as a hidden property with the specified value.
* </p>
*
* <p><i>
* This method was built for hiding configuration values, but it can be applied
* to <u>any</u> javascript object.
* </i></p>
*
* <p>Example:</p>
* <pre>
* var CONFIG = require('config');
* ...
*
* // Hide the Amazon S3 credentials
* CONFIG.util.makeHidden(CONFIG.amazonS3, 'access_id');
* CONFIG.util.makeHidden(CONFIG.amazonS3, 'secret_key');
* </pre>
*
* @method makeHidden
* @param object {object} - The object to make a hidden property into.
* @param property {string} - The name of the property to make hidden.
* @param value {mixed} - (optional) Set the property value to this (otherwise leave alone)
* @return object {object} - The original object is returned - for chaining.
*/
util.makeHidden = function(object, property, value) {
// If the new value isn't specified, just mark the property as hidden
if (typeof value === 'undefined') {
Object.defineProperty(object, property, {
enumerable : false
});
}
// Otherwise set the value and mark it as hidden
else {
Object.defineProperty(object, property, {
value : value,
enumerable : false
});
}
return object;
}
/**
* <p>Make a javascript object property immutable (assuring it cannot be changed
* from the current value).</p>
* <p>
* If the specified property is an object, all attributes of that object are
* made immutable, including properties of contained objects, recursively.
* If a property name isn't supplied, all properties of the object are made
* immutable.
* </p>
* <p>
*
* </p>
* <p>
* New properties can be added to the object and those properties will not be
* immutable unless this method is called on those new properties.
* </p>
* <p>
* This operation cannot be undone.
* </p>
*
* <p>Example:</p>
* <pre>
* var config = require('config');
* var myObject = {hello:'world'};
* config.util.makeImmutable(myObject);
* </pre>
*
* @method makeImmutable
* @param object {object} - The object to specify immutable properties for
* @param [property] {string | [string]} - The name of the property (or array of names) to make immutable.
* If not provided, all owned properties of the object are made immutable.
* @param [value] {mixed | [mixed]} - Property value (or array of values) to set
* the property to before making immutable. Only used when setting a single
* property. Retained for backward compatibility.
* @return object {object} - The original object is returned - for chaining.
*/
util.makeImmutable = function(object, property, value) {
var properties = null;
// Backwards compatibility mode where property/value can be specified
if (typeof property === 'string') {
return Object.defineProperty(object, property, {
value : (typeof value === 'undefined') ? object[property] : value,
writable : false,
configurable: false
});
}
// Get the list of properties to work with
if (Array.isArray(property)) {
properties = property;
}
else {
properties = Object.keys(object);
}
// Process each property
for (var i = 0; i < properties.length; i++) {
var propertyName = properties[i],
value = object[propertyName];
Object.defineProperty(object, propertyName, {
value: value,
writable : false,
configurable: false
});
// Call recursively if an object.
if (util.isObject(value)) {
util.makeImmutable(value);
}
}
return object;
};
/**
* Return the sources for the configurations
*
* <p>
* All sources for configurations are stored in an array of objects containing
* the source name (usually the filename), the original source (as a string),
* and the parsed source as an object.
* </p>
*
* @method getConfigSources
* @return configSources {Array[Object]} - An array of objects containing
* name, original, and parsed elements
*/
util.getConfigSources = function() {
var t = this;
return configSources.slice(0);
};
/**
* Load the individual file configurations.
*
* <p>
* This method builds a map of filename to the configuration object defined
* by the file. The search order is:
* </p>
*
* <pre>
* default.EXT
* (deployment).EXT
* (hostname).EXT
* (hostname)-(deployment).EXT
* local.EXT
* local-(deployment).EXT
* runtime.json
* </pre>
*
* <p>
* EXT can be yml, yaml, coffee, iced, json, cson or js signifying the file type.
* yaml (and yml) is in YAML format, coffee is a coffee-script, iced is iced-coffee-script,
* json is in JSON format, cson is in CSON format, properties is in .properties format
* (http://en.wikipedia.org/wiki/.properties), and js is a javascript executable file that is
* require()'d with module.exports being the config object.
* </p>
*
* <p>
* hostname is the $HOST environment variable (or --HOST command line parameter)
* if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command
* line parameter) if set, otherwise the hostname found from
* require('os').hostname().
* </p>
*
* <p>
* Once a hostname is found, everything from the first period ('.') onwards
* is removed. For example, abc.example.com becomes abc
* </p>
*
* <p>
* (deployment) is the deployment type, found in the $NODE_ENV environment
* variable or --NODE_ENV command line parameter. Defaults to 'development'.
* </p>
*
* <p>
* The runtime.json file contains configuration changes made at runtime either
* manually, or by the application setting a configuration value.
* </p>
*
* <p>
* If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE
* command line parameter) is set, then files with this appendage will be loaded.
* See the Multiple Application Instances section of the main documentaion page
* for more information.
* </p>
*
* @protected
* @method loadFileConfigs
* @return config {Object} The configuration object
*/
util.loadFileConfigs = function() {
// Initialize
var t = this,
config = {};
// Initialize parameters from command line, environment, or default
NODE_ENV = util.initParam('NODE_ENV', 'development');
CONFIG_DIR = util.initParam('NODE_CONFIG_DIR', Path.join( process.cwd(), 'config') );
if (CONFIG_DIR.indexOf('.') === 0) {
CONFIG_DIR = Path.join(process.cwd() , CONFIG_DIR);
}
APP_INSTANCE = util.initParam('NODE_APP_INSTANCE');
HOST = util.initParam('HOST');
HOSTNAME = util.initParam('HOSTNAME');
// This is for backward compatibility
RUNTIME_JSON_FILENAME = util.initParam('NODE_CONFIG_RUNTIME_JSON', Path.join(CONFIG_DIR , 'runtime.json') );
// Determine the host name from the OS module, $HOST, or $HOSTNAME
// Remove any . appendages, and default to null if not set
try {
var hostName = HOST || HOSTNAME;
// Store the hostname that won.
env.HOSTNAME = hostName;
if (!hostName) {
var OS = require('os');
hostName = OS.hostname();
}
} catch (e) {
hostName = '';
}
// Read each file in turn
var baseNames = ['default', NODE_ENV];
// #236: Also add full hostname when they are different.
if ( hostName ) {
var firstDomain = hostName.split('.')[0];
// Backward compatibility
baseNames.push(firstDomain, firstDomain + '-' + NODE_ENV);
// Add full hostname when it is not the same
if ( hostName != firstDomain ) {
baseNames.push(hostName, hostName + '-' + NODE_ENV);
}
}
baseNames.push('local', 'local-' + NODE_ENV);
var extNames = ['js', 'json', 'json5', 'hjson', 'toml', 'coffee', 'iced', 'yaml', 'yml', 'cson', 'properties'];
baseNames.forEach(function(baseName) {
extNames.forEach(function(extName) {
// Try merging the config object into this object
var fullFilename = Path.join(CONFIG_DIR , baseName + '.' + extName);
var configObj = util.parseFile(fullFilename);
if (configObj) {
util.extendDeep(config, configObj);
}
// See if the application instance file is available
if (APP_INSTANCE) {
fullFilename = Path.join(CONFIG_DIR, baseName + '-' + APP_INSTANCE + '.' + extName);
configObj = util.parseFile(fullFilename);
if (configObj) {
util.extendDeep(config, configObj);
}
}
});
});
// Override configurations from the $NODE_CONFIG environment variable
var envConfig = {};
if (process.env.NODE_CONFIG) {
try {
envConfig = JSON.parse(process.env.NODE_CONFIG);
} catch(e) {
console.error('The $NODE_CONFIG environment variable is malformed JSON');
}
util.extendDeep(config, envConfig);
configSources.push({
name: "$NODE_CONFIG",
parsed: envConfig,
});
}
// Override configurations from the --NODE_CONFIG command line
var cmdLineConfig = util.getCmdLineArg('NODE_CONFIG');
if (cmdLineConfig) {
try {
cmdLineConfig = JSON.parse(cmdLineConfig);
} catch(e) {
console.error('The --NODE_CONFIG={json} command line argument is malformed JSON');
}
util.extendDeep(config, cmdLineConfig);
configSources.push({
name: "--NODE_CONFIG argument",
parsed: cmdLineConfig,
});
}
// Override with environment variables if there is a custom-environment-variables.EXT mapping file
var customEnvVars = util.getCustomEnvVars(CONFIG_DIR, extNames);
util.extendDeep(config, customEnvVars);
// Place the mixed NODE_CONFIG into the environment
env['NODE_CONFIG'] = JSON.stringify(util.extendDeep(envConfig, cmdLineConfig, {}));
// Extend the original config with the contents of runtime.json (backwards compatibility)
var runtimeJson = util.parseFile(RUNTIME_JSON_FILENAME) || {};
util.extendDeep(config, runtimeJson);
util.resolveDeferredConfigs(config);
// Return the configuration object
return config;
};
// Using basic recursion pattern, find all the deferred values and resolve them.
util.resolveDeferredConfigs = function (config) {
var completeConfig = config;
function _iterate (prop) {
for (var property in prop) {
if (prop.hasOwnProperty(property) && prop[property] != null) {
if (prop[property].constructor == Object) {
_iterate(prop[property]);
} else if (prop[property].constructor == Array) {
for (var i = 0; i < prop[property].length; i++) {
_iterate(prop[property][i]);
}
} else {
if (prop[property] instanceof DeferredConfig ) {
prop[property]= prop[property].resolve.call(completeConfig,completeConfig)
}
else {
// Nothing to do. Keep the property how it is.
}
}
}
}
}
_iterate(config);
}
/**
* Parse and return the specified configuration file.
*
* If the file exists in the application config directory, it will
* parse and return it as a JavaScript object.
*
* The file extension determines the parser to use.
*
* .js = File to run that has a module.exports containing the config object
* .coffee = File to run that has a module.exports with coffee-script containing the config object
* .iced = File to run that has a module.exports with iced-coffee-script containing the config object
* All other supported file types (yaml, toml, json, cson, hjson, json5, properties)
* are parsed with util.parseString.
*
* If the file doesn't exist, a null will be returned. If the file can't be
* parsed, an exception will be thrown.
*
* This method performs synchronous file operations, and should not be called
* after synchronous module loading.
*
* @protected
* @method parseFile
* @param fullFilename {string} The full file path and name
* @return {configObject} The configuration object parsed from the file
*/
util.parseFile = function(fullFilename) {
// Initialize
var t = this,
extension = fullFilename.substr(fullFilename.lastIndexOf('.') + 1),
configObject = null,
fileContent = null;
// Return null if the file doesn't exist.
// Note that all methods here are the Sync versions. This is appropriate during
// module loading (which is a synchronous operation), but not thereafter.
try {
var stat = FileSystem.statSync(fullFilename);
if (!stat || stat.size < 1) {
return null;
}
} catch (e1) {
return null
}
// Try loading the file.
try {
fileContent = FileSystem.readFileSync(fullFilename, 'UTF-8');
fileContent = fileContent.replace(/^\uFEFF/, '');
}
catch (e2) {
throw new Error('Config file ' + fullFilename + ' cannot be read');
}
// Parse the file based on extension
try {
if (extension === 'js') {
// Use the built-in parser for .js files
configObject = require(fullFilename);
}
else if (extension === 'coffee') {
// .coffee files can be loaded with either coffee-script or iced-coffee-script.
// Prefer iced-coffee-script, if it exists.
// Lazy load the appropriate extension
if (!Coffee) {
Coffee = {};
// The following enables iced-coffee-script on .coffee files, if iced-coffee-script is available.
// This is commented as per a decision on a pull request.
//try {
// Coffee = require("iced-coffee-script");
//}
//catch (e) {
// Coffee = require("coffee-script");
//}
Coffee = require("coffee-script");
// coffee-script >= 1.7.0 requires explicit registration for require() to work
if (Coffee.register) {
Coffee.register();
}
}
// Use the built-in parser for .coffee files with coffee-script
configObject = require(fullFilename);
}
else if (extension === 'iced') {
Iced = require("iced-coffee-script");
// coffee-script >= 1.7.0 requires explicit registration for require() to work
if (Iced.register) {
Iced.register();
}
}
else {
configObject = util.parseString(fileContent, extension);
}
}
catch (e3) {
throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3);
}
// Keep track of this configuration sources, including empty ones
if (typeof configObject === 'object') {
configSources.push({
name: fullFilename,
original: fileContent,
parsed: configObject,
});
}
return configObject;
};
/**
* Parse and return the specied string with the specified format.
*
* The format determines the parser to use.
*
* json = File is parsed using JSON.parse()
* yaml (or yml) = Parsed with a YAML parser
* toml = Parsed with a TOML parser
* cson = Parsed with a CSON parser
* hjson = Parsed with a HJSON parser
* json5 = Parsed with a JSON5 parser
* properties = Parsed with the 'properties' node package
*
* If the file doesn't exist, a null will be returned. If the file can't be
* parsed, an exception will be thrown.
*
* This method performs synchronous file operations, and should not be called
* after synchronous module loading.
*
* @protected
* @method parseString
* @param content {string} The full content
* @param format {string} The format to be parsed
* @return {configObject} The configuration object parsed from the string
*/
util.parseString = function (content, format) {
// Initialize
var configObject = null;
// Parse the file based on extension
if (format === 'yaml' || format === 'yml') {
if (!Yaml && !VisionmediaYaml) {
// Lazy loading
try {
// Try to load the better js-yaml module
Yaml = require('js-yaml');
}
catch (e) {
try {
// If it doesn't exist, load the fallback visionmedia yaml module.
VisionmediaYaml = require('yaml');
}
catch (e) { }
}
}
if (Yaml) {
configObject = Yaml.load(content);
}
else if (VisionmediaYaml) {
// The yaml library doesn't like strings that have newlines but don't
// end in a newline: https://github.com/visionmedia/js-yaml/issues/issue/13
content += '\n';
configObject = VisionmediaYaml.eval(util.stripYamlComments(content));
}
else {
console.error("No YAML parser loaded. Suggest adding js-yaml dependency to your package.json file.")
}
}
else if (format === 'json') {
try {
configObject = JSON.parse(content);
}
catch (e) {
// All JS Style comments will begin with /, so all JSON parse errors that
// encountered a syntax error will complain about this character.
if (e.name !== 'SyntaxError' || e.message !== 'Unexpected token /') {
throw e;
}
if (!JSON5) {
JSON5 = require('json5');
}
configObject = JSON5.parse(content);
}
}
else if (format === 'json5') {
if (!JSON5) {
JSON5 = require('json5');
}
configObject = JSON5.parse(content);
} else if (format === 'hjson') {
if (!HJSON) {
HJSON = require('hjson');
}
configObject = HJSON.parse(content);
} else if (format === 'toml') {
if(!TOML) {
TOML = require('toml');
}
configObject = TOML.parse(content);
}
else if (format === 'cson') {
if (!CSON) {
CSON = require('cson');
}
// Allow comments in CSON files
if (typeof CSON.parseSync === 'function') {
configObject = CSON.parseSync(util.stripComments(content));
} else {
configObject = CSON.parse(util.stripComments(content));
}