pax_global_header 0000666 0000000 0000000 00000000064 14134613066 0014516 g ustar 00root root 0000000 0000000 52 comment=98f2fc9bd634f6dab61bc1a0003de4dbf8f9a9ad node-config-3.3.7/ 0000775 0000000 0000000 00000000000 14134613066 0013720 5 ustar 00root root 0000000 0000000 node-config-3.3.7/.editorconfig 0000664 0000000 0000000 00000000027 14134613066 0016374 0 ustar 00root root 0000000 0000000 [*.js] indent_size = 2 node-config-3.3.7/.gitignore 0000664 0000000 0000000 00000000051 14134613066 0015704 0 ustar 00root root 0000000 0000000 .project node_modules npm-debug.log .idea node-config-3.3.7/.npmignore 0000664 0000000 0000000 00000000055 14134613066 0015717 0 ustar 00root root 0000000 0000000 node_modules test tools ISSUE_TEMPLATE.md .* node-config-3.3.7/.npmrc 0000664 0000000 0000000 00000000130 14134613066 0015032 0 ustar 00root root 0000000 0000000 # Prevent accidental publish to private repository registry=https://registry.npmjs.org/ node-config-3.3.7/.travis.yml 0000664 0000000 0000000 00000000161 14134613066 0016027 0 ustar 00root root 0000000 0000000 language: node_js sudo: false before_install: - npm update -g npm node_js: - "10" - "12" - "14" - "15" node-config-3.3.7/History.md 0000664 0000000 0000000 00000045342 14134613066 0015713 0 ustar 00root root 0000000 0000000 3.3.6 / 2021-03-08 ================== * Added publishConfig element to package.json to prevent publishing to the wrong repository - @lorenwest 3.3.5 / 2021-03-05 ================== * FIX [#628](https://github.com/lorenwest/node-config/issues/628) Uncaught ReferenceError: node_env_var_name is not defined @prnake 3.3.4 / 2021-02-26 ================== * FIX #517 0 loadFileConfigs incorrectly adds to getConfigSources @NguyenMatthieu 3.3.3 / 2020-11-26 ================== * FIX #460 - Strict mode warning refer to appropriate env variable @iCodeOkay * Use Buffer.alloc and Buffer.from instead of contrsuctor @Fcmam5 * Add support for experimental .cjs modules @lenkan 3.3.2 / 2020-09-24 ================== * Fixed issue with Buffers in config throwing error in util.makeImmutable (#608) - Michal Wadas * Added boolean and numeric types to custom environment variables - Ankur Narkhede @ankurnarkhede 3.3.1 / 2020-03-25 ================== * Fix security vulnerability in json5 dependency - @twkel 3.3.0 / 2020-02-26 ================== * Allow all defined values in `substituteDeep` - @fostyfost 3.2.6 / 2020-02-21 ================== * Updated copyright date ranges 3.2.5 / 2020-01-16 ================== * Fixed issue with getCustomEnvVars and multiple config dirs #585 - @dekelev 3.2.4 / 2019-10-25 ================== * Improved error handling of env variables value parse - @leonardovillela 3.2.3 / 2019-10-03 ================== * Fixed strict mode warning #460 - @fedulovivan 3.2.2 / 2019-07-20 ================== * Fixed delimiter bug in configDirs to match O/S delimiter - @iMoses 3.2.1 / 2019-07-18 ================== * Fixed TypeError: obj.toString is not a function - @leosuncin 3.2.0 / 2019-07-11 ================== * Asynchronous configs - @iMoses * Multiple config directories - @iMoses * Improved parser support - @iMoses 3.1.0 / 2019-04-07 ================== * Support of module.exports syntax for TS config files @keenondrums 3.0.1 / 2018-12-16 ================== * Fixed bug where dot notation extended own key @exogen 3.0.0 / 2018-11-20 ================== * Ensure config array items and objects are sealed @fgheorghe - This required a major version bump in case someone - relied on the ability to mutate non-sealed data. 2.0.2 / 2018-08-28 ================== * Added dot notation to setModuleDefaults - bertho-zero * Updated copyright year - JemiloII 2.0.1 / 2018-07-26 ================== * Removed deprecated code - jpwilliams 2.0.0 / 2018-07-26 ================== Potential for backward incompatibility requiring a major version bump. Safe to upgrade to major version 2 if you're using a recent NodeJS version and you're not trying to mutate config arrays. * Added array immutability - jacobemerick * Removed Node V.4 support 1.31.0 / 2018-05-22 =================== * Load new coffeescript module instead of coffee-script - bastbijl 1.30.0 / 2018-02-26 =================== * Support for nested raw() in javascript configurations - patrickpilch 1.29.4 / 2018-02-03 =================== * Re-publish - last changes didn't make it to npm 1.29.3 / 2018-02-03 =================== * Added soft dependencies so transpilers don't include everything - gewentao 1.29.2 / 2018-01-12 =================== * Patch, and added a test to ts-node - electroma 1.29.1 / 2018-01-07 =================== * Prevent re-registration of ts-node - electroma * Fixed bug in contributor table tool - lorenwest 1.29.0 / 2017-12-26 =================== * Update docs for JavaScript-formatted config files and link them from the README - markstos * Fixed 'hostname' value selection when there is no environment variable for that - wmangelardo 1.28.1 / 2017-11-09 =================== * add nodejs9 to travisci - jfelege 1.28.0 / 2017-11-07 =================== * allow overrides of `NODE_ENV` with `NODE_CONFIG_ENV` - jfelege 1.27.0 / 2017-10-17 =================== * Add method to output plain JS object - willsoto * Updated Node versions in Travis CI - lorenwest 1.26.2 / 2017-08-11 =================== * Update supported nodejs platforms - jfelege 1.26.1 / 2017-05-03 =================== * Fix: failed while merging from RegExp @XadillaX * Chore: reduce package size. @evilebottnawi 1.26.0 / 2017-03-30 =================== * Added tests for extendDeep @IvanVergiliev * Added TypeScript support @cypherq * Update config.js with correctly cased type def @ScionOfBytes 1.25.1 / 2017-02-01 =================== * Fixed undefined CONFIG_SKIP_GITCRYPT variable @lorenwest 1.25.0 / 2017-01-31 =================== * Add support for configuration files stored with git-crypt @cunneen 1.24.0 / 2016-11-02 =================== * Prevent accidental publish to private repository 1.23.0 / 2016-11-02 =================== * Re-publishing because npmjs didn't see 1.22 1.22.0 / 2016-10-25 =================== * original/previous value for deferredConfig @simon-scherzinger * util.loadFileConfigs: support optional source dir @wmertens * Adding raw wrapper to prevent object modification in config @patrickpilch 1.21.0 / 2016-06-01 =================== * Added XML configuration @tusharmath 1.20.4 / 2016-05-23 =================== * Fixed a regression with extending prototype methods @tahoemph 1.20.3 / 2016-05-18 =================== * Fixed a regression with 1.20.2 @kgoerlitz * Added test to prevent this in the future @kgoerlitz 1.20.2 / 2016-05-17 =================== * node v6 compatiblity: remove deprecated __lookupGetter__ use - @thetalecrafter * node v6 compatiblity: handle different SyntaxError format - @pwwolf 1.20.1 / 2016-04-08 =================== * Simplify truthiness check - @markstos * Remove errant console.log - @markstos 1.20.0 / 2016-04-06 =================== * Typo fix @jchip * Handle null sub-object @wmertens * Bug fix for NODE_CONFIG_STRICT_MODE check @markstos * Ran node security check on 4/6/2016 with the following output $ nsp check (+) No known vulnerabilities found 1.19.0 / 2016-01-08 =================== * Resolve defered values in predictable order for consistent results. Fixes #265 @elliotttf @markstos 1.18.0 / 2015-11-17 =================== * More robust handling of JSON @elliotttf 1.17.1 / 2015-11-17 =================== * Patch release for regex bugfix 1.17.0 / 2015-11-17 =================== * Update warning about missing configuration files to mention how to disable the warning #245 @markstos * Upgrade to run CI with travis containers @lorenwest * Fixed bug with comments and inline json @elliotttf 1.16.0 / 2015-09-03 =================== * Change == to === to tighten equality tests #242 @wgpsutherland * Fix attachProtoDeep for setModuleDefaults #243 @benkroeger 1.15.0 / 2015-07-30 =================== * Added full hostname in addition to first segment @vicary 1.14.0 / 2015-06-02 =================== * Added JSON parsing to custom environment variables @leachiM2k * Handle unicode BOM characters @johndkane 1.13.0 / 2015-05-05 =================== * Updated CSON library @dsimidzija 1.12.0 / 2015-02-19 =================== * Better date merging @axelhzf 1.11.0 / 2015-01-14 =================== * Added Hjson support @laktak 1.10.0 / 2015-01-06 =================== * Added TOML support (@jasonhansel) * Another year - changed copyright messages for 2015 * Updated contributors list * New Strict Mode added in 1.9.0 is now documented. (@markstos) * has() now returns false when given an undefined or null key to look up. Previously it threw an exception. (@markstos) * When get() is given an undefined or null key to look up, it now throws a more helpful diagnostic (@robludwig, @markstos) 1.9.0 / 2014-12-08 ================== * New strictness checks have been added to ensure the expected configuration has been loaded. Warnings are now thrown in these cases. If NODE_CONFIG_STRICT_MODE is set, exceptions are thrown instead. (@markstos) * There must be an explicit config file matching `NODE_ENV` if `NODE_ENV` is set. * There must be an explicit config file matching `NODE_APP_INSTANCE` if `NODE_APP_INSTANCE` is set * `NODE_ENV` must not match 'default' or 'local' to avoid ambiguity. * Added .iced extension support (@arthanzel) * Highlight `config.has()` in the README. Use it to check to if a value exists, since `config.get()` throws exceptions on undefined values. (@markstos) * API Change: getConfigSources() now starts to return data on config files that are valid-but-empty. (@markstos) 1.8.1 / 2014-11-14 ================== * Simplify syntax for defer() functions. The 'this' value in the functions is now bound to the main configuration object, so it doesn't have to be passed into the function. (@markstos) * new defer sub-module introduced in 1.8.0 can now be accessed by require('config/defer') For usage, see: https://github.com/lorenwest/node-config/wiki/Configuration-Files#javascript-module---js * Add test coverage for array merging cases. (@markstos) * Bump dependency on cson package to 1.6.1 (@markstos) 1.8.0 / 2014-11-13 ================== * Added deferred function for evaluating configs after load (@markstos) For details, see: https://github.com/lorenwest/node-config/wiki/Configuration-Files#javascript-module---js * Bumped js-yaml dependency (@markstos) 1.7.0 / 2014-10-30 ================== * Added variable substitution in .properties files (@ncuillery) 1.6.0 / 2014-10-22 ================== * Added support for property accessors in configs (@jaylynch) 1.5.0 / 2014-10-20 ================== * Added support for .json5 config files (@bertrandom) 1.4.0 / 2014-10-16 ================== * Added support for .properties config files (@superoven) 1.3.0 / 2014-10-15 ================== * Added support for CSON configuration files (@superoven) 1.2.4 / 2014-10-10 ================== * Repaired the 1.2.3 fix to work both before and after the first get() 1.2.3 / 2014-10-03 ================== * Changed test suite to verify a bug in util.setModuleDefaults() * Fixed util.setModuleDefaults() to work after a get() (and pass the new test) 1.2.2 / 2014-10-03 ================== * Added support for regexp and date configurations (@diversario) 1.2.1 / 2014-09-23 ================== * Wrote test to prove setModuleDefaults() was broken in 1.2.0 * Fixed setModuleDefaults() to not rely on immutable configs 1.2.0 / 2014-09-15 ================== * Feature release * Delaying immutability until after first get() - for external configs * Allowing immutability override with $ALLOW_CONFIG_MUTATIONS=Y 1.1.1 / 2014-09-03 ================== * @th507 - Update support for Coffee-script >=1.7.0 1.1.0 / 2014-09-03 ================== * Feature release * @bradboro - Custom environment variables * @supersheep - Catch error when requiring visionmedia yaml module 1.0.2 / 2014-07-30 =================== * @bradobro - Fixed a variable from leaking into global * @tilfin - Removed un-necessary YAML comment filtering for js-yaml 1.0.1 / 2014-07-25 =================== * Removed test directory from npm install 1.0.0 / 2014-07-23 =================== * Major revision. Upgrade notes: https://github.com/lorenwest/node-config/wiki/Upgrading-From-Config-0.x * Update to semver versioning * Change load ordering from hostname.EXT --> deployment.EXT to deployment.EXT --> hostname.EXT * Allow makeImmutable to accept an array of attributes * Allow makeImmutable to accept no attrs, making all attributes immutable * Allow recursion in makeImmutable, if an attribute is an object * Change node-config behavior to make all configurations immutable * Removed getOriginalConfig as no longer necessary post-immutable * Removed runtime.json file writing and monitoring * Removed previously deprecated $CONFIG_* environment configurations * Deprecated the attribute watch functionality * Added error output if no configurations found * Exposed config loading for alternate configurations * Added config.get() and config.has() methods & tests * Removed reliance on global.NODE_CONFIG so older versions can work with 1.x * Fix empty YAML file causing crash with latest js-yaml * Added SUPPRESS_NO_CONFIG_WARNING for better sub-module support * Moved all documentation [to the wiki](https://github.com/lorenwest/node-config/wiki). 0.4.37 / 2014-07-22 =================== * Fix empty YAML file causing crash with latest js-yaml 0.4.36 / 2014-05-27 =================== * Not writing runtime.json if not used 0.4.35 / 2014-01-16 =================== * NODE_CONFIG_DIR can now contain a relative path for .js and .coffee configurations 0.4.34 / 2014-01-06 =================== * Updated copyright year 0.4.33 / 2013-10-25 =================== * Assure writes to runtime.json are atomic 0.4.32 / 2013-10-24 =================== * Don't freak out if running without a config directory * Don't be so chatty if runtime.json doesn't exist 0.4.31 / 2013-10-18 =================== * Changed getConfigSources to copy array vs. object 0.4.30 / 2013-09-12 =================== * More consistent array extension * No longer requiring a config directory * Not erroneously writing runtime.json * Exposing the original configuration sources * Added --NODE_CONFIG={json} command line overrides * Added $NODE_CONFIG={json} environment variable overrides * Consistent handling of environment variables and command line parameters * Reached 100 regression tests 0.4.29 / 2013-08-07 =================== * Added flag for disabling the write of runtime.json 0.4.28 / 2013-07-31 =================== * Eliminated a totally annoying install warning in newer versions of NPM 0.4.27 / 2013-06-18 =================== * Fixed a bug preventing double underscores in config environment variables 0.4.26 / 2013-06-10 =================== * Re-watch file on rename (allows editing runtime.json with vi) * Allow runtime.json file watch disable via NODE_CONFIG_DISABLE_FILE_WATCH=Y * Change no yaml parser error message to suggest using js-yaml * Changed default clone depth from 6 to 20 to allow for deeper configurations 0.4.25 / 2013-05-24 =================== * Dont fail if config directory doesnt exist 0.4.24 / 2013-04-13 =================== * Added resetRuntime() to reset the runtime.json file * Updated docs to reflect the new public method 0.4.23 / 2013-04-13 =================== * Multiple application instance support via $NODE_APP_INSTANCE * Multi-app testing & documentation 0.4.22 / 2013-03-29 =================== * Added configuration $CONFIG_* environment variables * Added $CONFIG_* documentation and tests * Added NodeJS 0.10 integration test 0.4.21 / 2013-03-06 =================== * Triggering file.watch when an editor saves a file - rename vs. change * Installed Travis-CI continuous integration testing framework 0.4.20 / 2013-02-21 =================== * Merged _diffDeep fix 0.4.19 / 2013-02-21 =================== * Added discovery of .yml in addition to .yaml for YAML configs (w/doc) * Added testing of .yml file discovery * Removed licensing inconsistencies 0.4.18 / 2012-10-30 =================== * Moved coffee-script and js-yaml from optionalDependencies back to devDependencies to trim the install size for those not needing these packages. * Promoted $HOSTNAME and $HOST above OS.hostname() 0.4.17 / 2012-09-26 =================== * Allow the location of runtime.json to be picked up from the environment * Added documentation for the NODE_CONFIG_RUNTIME_JSON environment variable * package.json cleanup - created optionalDependencies and devDependencies 0.4.16 / 2012-08-09 =================== * Allowing a zero interval in watchForConfigFileChanges() to disable file watching. * Fixed a comparator bug in _equalsDeep() * Added a test to confirm deep extending array functionality 0.4.15 / 2012-06-04 =================== * Placed YAML and Coffee-Script libraries back into the download. Still lazy loading into memory. 0.4.14 / 2012-06-01 =================== * Added the local.EXT and local-deployment.EXT configs. * Removed unnecessary debug output * Added retry logic on file parse to reduce read/write collisions * Added support for a better YAML parser * Fixed problems with null configuration values 0.4.13 / 2012-04-25 =================== * Assuring the runtime.json file exists. Undocumented fs.watch() requirement. 0.4.12 / 2012-04-25 =================== * Removed all external dependencies * Lazy loading of yaml and coffee-script only if these file types are used * Added new style file watching if available (retaining pre 6.0 compatibility) * Windows compatibility - file watching changes were required 0.4.11 / 2012-02-15 =================== * Automatically watching runtime.json for changes * Fixed a date comparison bug during file watching * Changed require('sys') to require('util') 0.4.10 / 2012-01-18 =================== * Made sure the CONFIG object is a shared singleton * Added NODE_CONFIG_DIR environment variable to point to a different directory * Added tests and documentation for the above 0.4.9 / 2012-01-06 ================== * Added coffee-script file type support with extension .coffee * Added an example coffee-script configuration file * Added coffee-script module dependency * Added a test for coffee-script configuration files * Documented coffee-script support, regenerated documentation 0.4.8 / 2011-12-20 ================== * Fixed a bug where changes to module default configs weren't persisted * Added a test to validate the bugfix 0.4.7 / 2011-12-16 ================== * Created the makeHidden method to hide a property of an object * Added a value argument to makeImmutable for creating new properties * Fixed setModuleDefaults to hide injected prototype methods * Added documentation and unit tests 0.4.6 / 2011-11-29 ================== * Updated vows from 0.5.8 to 0.5.13 0.4.5 / 2011-11-16 ================== * Updated YAML dependency from "0.1.x" to ">=0.2.2" * Added stripping of comment-only and whitespace-only lines in YAML files for backward compatibility * Added more tests for YAML edge cases * Added a homepage link in package.json to the online documentation * Added History.md 0.4.4 / 2011-11-08 ================== * Removed deprecated modules from package.json 0.4.3 / 2011-08-02 ================== * Made watchForConfigFileChanges public 0.4.2 / 2011-07-11 ================== * Added comment stripping from JSON configuration files 0.4.1 / 2011-07-07 ================== * Added more tests * Return the module config in setModuleDefaults 0.4.0 / 2011-07-06 ================== * Update to version 0.4.0 * Online documentation * Runtime configuration changes * Configuration value watching * Multi-instance node deployments * Better module developer support node-config-3.3.7/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000001755 14134613066 0016435 0 ustar 00root root 0000000 0000000 **Note: for support questions, please use [StackOverflow](https://stackoverflow.com/questions/tagged/node-config) and tag your question with `node-config`**. *This repository's issues are reserved for feature requests and bug reports.* Before submitting a bug report, please search the issue tracker the wiki first. Many issues have already been discussed. The wiki is located at: https://github.com/lorenwest/node-config/wiki ### I'm submitting a ... - [ ] bug report - [ ] feature request - [ ] support request or question => Please do not submit support request or questions here, see note at the top of this template. ### What is the current behavior? *If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem*: ### What is the expected behavior? ### Please tell us about your environment: - node-config version: x.x.x - node-version: x.x.x ### Other information (e.g. are you using an environment besides Node.js?) node-config-3.3.7/LICENSE 0000664 0000000 0000000 00000002153 14134613066 0014726 0 ustar 00root root 0000000 0000000 // Copyright 2010-2020, Loren West and other contributors // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. node-config-3.3.7/README.md 0000664 0000000 0000000 00000022347 14134613066 0015207 0 ustar 00root root 0000000 0000000 Configure your Node.js Applications =================================== [](https://nodei.co/npm/config/) [](https://travis-ci.org/lorenwest/node-config) [release notes](https://github.com/lorenwest/node-config/blob/master/History.md) Introduction ------------ Node-config organizes hierarchical configurations for your app deployments. It lets you define a set of default parameters, and extend them for different deployment environments (development, qa, staging, production, etc.). Configurations are stored in [configuration files](https://github.com/lorenwest/node-config/wiki/Configuration-Files) within your application, and can be overridden and extended by [environment variables](https://github.com/lorenwest/node-config/wiki/Environment-Variables), [command line parameters](https://github.com/lorenwest/node-config/wiki/Command-Line-Overrides), or [external sources](https://github.com/lorenwest/node-config/wiki/Configuring-from-an-External-Source). This gives your application a consistent configuration interface shared among a [growing list of npm modules](https://www.npmjs.org/browse/depended/config) also using node-config. Project Guidelines ------------------ * *Simple* - Get started fast * *Powerful* - For multi-node enterprise deployment * *Flexible* - Supporting multiple config file formats * *Lightweight* - Small file and memory footprint * *Predictable* - Well tested foundation for module and app developers Quick Start --------------- The following examples are in JSON format, but configurations can be in other [file formats](https://github.com/lorenwest/node-config/wiki/Configuration-Files#file-formats). **Install in your app directory, and edit the default config file.** ```shell $ npm install config $ mkdir config $ vi config/default.json ``` ```js { // Customer module configs "Customer": { "dbConfig": { "host": "localhost", "port": 5984, "dbName": "customers" }, "credit": { "initialLimit": 100, // Set low for development "initialDays": 1 } } } ``` **Edit config overrides for production deployment:** ```shell $ vi config/production.json ``` ```json { "Customer": { "dbConfig": { "host": "prod-db-server" }, "credit": { "initialDays": 30 } } } ``` **Use configs in your code:** ```js const config = require('config'); //... const dbConfig = config.get('Customer.dbConfig'); db.connect(dbConfig, ...); if (config.has('optionalFeature.detail')) { const detail = config.get('optionalFeature.detail'); //... } ``` `config.get()` will throw an exception for undefined keys to help catch typos and missing values. Use `config.has()` to test if a configuration value is defined. **Start your app server:** ```shell $ export NODE_ENV=production $ node my-app.js ``` Running in this configuration, the `port` and `dbName` elements of `dbConfig` will come from the `default.json` file, and the `host` element will come from the `production.json` override file. Articles -------- * [Configuration Files](https://github.com/lorenwest/node-config/wiki/Configuration-Files) * [Special features for JavaScript configuration files](https://github.com/lorenwest/node-config/wiki/Special-features-for-JavaScript-configuration-files) * [Common Usage](https://github.com/lorenwest/node-config/wiki/Common-Usage) * [Environment Variables](https://github.com/lorenwest/node-config/wiki/Environment-Variables) * [Reserved Words](https://github.com/lorenwest/node-config/wiki/Reserved-Words) * [Command Line Overrides](https://github.com/lorenwest/node-config/wiki/Command-Line-Overrides) * [Multiple Node Instances](https://github.com/lorenwest/node-config/wiki/Multiple-Node-Instances) * [Sub-Module Configuration](https://github.com/lorenwest/node-config/wiki/Sub-Module-Configuration) * [Configuring from a DB / External Source](https://github.com/lorenwest/node-config/wiki/Configuring-from-an-External-Source) * [Securing Production Config Files](https://github.com/lorenwest/node-config/wiki/Securing-Production-Config-Files) * [External Configuration Management Tools](https://github.com/lorenwest/node-config/wiki/External-Configuration-Management-Tools) * [Examining Configuration Sources](https://github.com/lorenwest/node-config/wiki/Examining-Configuration-Sources) * [Using Config Utilities](https://github.com/lorenwest/node-config/wiki/Using-Config-Utilities) * [Upgrading from Config 0.x](https://github.com/lorenwest/node-config/wiki/Upgrading-From-Config-0.x) * [Webpack usage](https://github.com/lorenwest/node-config/wiki/Webpack-Usage) Further Information --------------------- If you still don't see what you are looking for, here are some more resources to check: * The [wiki may have more pages](https://github.com/lorenwest/node-config/wiki) which are not directly linked from here. * Review [questions tagged with node-config](https://stackexchange.com/filters/207096/node-config) on StackExchange. These are monitored by `node-config` contributors. * [Search the issue tracker](https://github.com/lorenwest/node-config/issues). Hundreds of issues have already been discussed and resolved there. Contributors ------------
Application Configurations
* ** The config module exports a singleton object representing all * configurations for this application deployment. *
* ** 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.). *
* ** For example, with the following config/default.yaml file: *
* ** ... * customer: * initialCredit: 500 * db: * name: customer * port: 5984 * ... ** *
* The following code loads the customer section into the CONFIG variable: *
* *
* var CONFIG = require('config').customer; * ... * newCustomer.creditLimit = CONFIG.initialCredit; * database.open(CONFIG.db.name, CONFIG.db.port); * ... ** * @module config * @class Config */ /** *
Get the configuration object.
* ** The configuration object is a shared singleton object within the application, * attained by calling require('config'). *
* ** 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: *
** var CONFIG = require('config'); ** *
* 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: *
** var CONFIG = require('config').customer; * or * var CUSTOMER_CONFIG = require('config').customer; ** * * * @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) { if (typeof util[fnName] === 'function') { 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|string[]} - The property name to get (as an array or '.' delimited string) * @return value {*} - 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; } // Note that typeof null === 'object' if (value === null || typeof value !== 'object') { return undefined; } return getImpl(value, elems.slice(1)); }; /** *
Get a configuration value
* ** 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. *
* * @method get * @param property {string} - The configuration property to get. Can include '.' sub-properties. * @return value {*} - The property value */ Config.prototype.get = function(property) { if(property === null || property === undefined){ throw new Error("Calling config.get with null or undefined argument"); } // Make configurations immutable after first get (unless disabled) if (checkMutability) { if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) { util.makeImmutable(config); } checkMutability = false; } 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'); } // Return the value return value; }; /** * Test that a configuration parameter exists * ** var config = require('config'); * if (config.has('customer.dbName')) { * console.log('Customer database name: ' + config.customer.dbName); * } ** * @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); }; /** *
* Set default configurations for a node.js module. *
* ** This allows module developers to attach their configurations onto the * default configuration object so they can be configured by the consumers * of the module. *
* *Using the function within your module:
** var CONFIG = require("config"); * CONFIG.util.setModuleDefaults("MyModule", { * templateName: "t-50", * colorScheme: "green" * }); ** *
* // Template name may be overridden by application config files * console.log("Template: " + CONFIG.MyModule.templateName); *
* The above example results in a "MyModule" element of the configuration * object, containing an object with the specified default values. *
* * @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: {} }); } util.setPath(configSources[0].parsed, moduleName.split('.'), {}); util.extendDeep(getImpl(configSources[0].parsed, moduleName), defaultProperties); // Create a top level config for this module if it doesn't exist util.setPath(t, moduleName.split('.'), getImpl(t, moduleName) || {}); // Extend local configurations into the module config util.extendDeep(moduleConfig, getImpl(t, moduleName)); // Merge the extended configs without replacing the original util.extendDeep(getImpl(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(getImpl(t, moduleName)); }; /** *Make a configuration property hidden so it doesn't appear when enumerating * elements of the object.
* ** 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. *
* ** If the property already exists, it will be made hidden. Otherwise it will * be created as a hidden property with the specified value. *
* ** This method was built for hiding configuration values, but it can be applied * to any javascript object. *
* *Example:
** var CONFIG = require('config'); * ... * * // Hide the Amazon S3 credentials * CONFIG.util.makeHidden(CONFIG.amazonS3, 'access_id'); * CONFIG.util.makeHidden(CONFIG.amazonS3, 'secret_key'); ** * @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 {*} - (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; } /** *
Make a javascript object property immutable (assuring it cannot be changed * from the current value).
** 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. *
** *
** New properties can be added to the object and those properties will not be * immutable unless this method is called on those new properties. *
** This operation cannot be undone. *
* *Example:
** var config = require('config'); * var myObject = {hello:'world'}; * config.util.makeImmutable(myObject); ** * @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] {* | [*]} - 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) { if (Buffer.isBuffer(object)) { return object; } 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]; if (value instanceof RawConfig) { Object.defineProperty(object, propertyName, { value: value.resolve(), writable: false, configurable: false }); } else if (Array.isArray(value)) { // Ensure object items of this array are also immutable. value.forEach((item, index) => { if (util.isObject(item) || Array.isArray(item)) util.makeImmutable(item) }) Object.defineProperty(object, propertyName, { value: Object.freeze(value) }); } else { Object.defineProperty(object, propertyName, { value: value, writable : false, configurable: false }); // Ensure new properties can not be added. Object.preventExtensions(object) // Call recursively if an object. if (util.isObject(value)) { util.makeImmutable(value); } } } return object; }; /** * Return the sources for the configurations * *
* 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. *
* * @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); }; /** * Looks into an options object for a specific attribute * ** This method looks into the options object, and if an attribute is defined, returns it, * and if not, returns the default value *
* * @method getOption * @param options {Object | undefined} the options object * @param optionName {string} the attribute name to look for * @param defaultValue { any } the default in case the options object is empty, or the attribute does not exist. * @return options[optionName] if defined, defaultValue if not. */ util.getOption = function(options, optionName, defaultValue) { if (options !== undefined && options[optionName] !== undefined){ return options[optionName]; } else { return defaultValue; } }; /** * Load the individual file configurations. * ** This method builds a map of filename to the configuration object defined * by the file. The search order is: *
* ** default.EXT * (deployment).EXT * (hostname).EXT * (hostname)-(deployment).EXT * local.EXT * local-(deployment).EXT * runtime.json ** *
* 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. *
* ** 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(). *
* ** Once a hostname is found, everything from the first period ('.') onwards * is removed. For example, abc.example.com becomes abc *
* ** (deployment) is the deployment type, found in the $NODE_ENV environment * variable (which can be overridden by using $NODE_CONFIG_ENV * environment variable). Defaults to 'development'. *
* ** The runtime.json file contains configuration changes made at runtime either * manually, or by the application setting a configuration value. *
* ** 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 documentation page * for more information. *
* * @protected * @method loadFileConfigs * @param configDir { string | null } the path to the directory containing the configurations to load * @param options { object | undefined } parsing options. Current supported option: skipConfigSources: true|false * @return config {Object} The configuration object */ util.loadFileConfigs = function(configDir, options) { // Initialize var t = this, config = {}; // Specify variables that can be used to define the environment var node_env_var_names = ['NODE_CONFIG_ENV', 'NODE_ENV']; // Loop through the variables to try and set environment for (const node_env_var_name of node_env_var_names) { NODE_ENV = util.initParam(node_env_var_name); if (!!NODE_ENV) { NODE_ENV_VAR_NAME = node_env_var_name; break; } } // If we haven't successfully set the environment using the variables, we'll default it if (!NODE_ENV) { NODE_ENV = 'development'; } node_env_var_names.forEach(node_env_var_name => { env[node_env_var_name] = NODE_ENV; }); // Split files name, for loading multiple files. NODE_ENV = NODE_ENV.split(','); CONFIG_DIR = configDir || 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'); CONFIG_SKIP_GITCRYPT = util.initParam('CONFIG_SKIP_GITCRYPT'); // This is for backward compatibility RUNTIME_JSON_FILENAME = util.initParam('NODE_CONFIG_RUNTIME_JSON', Path.join(CONFIG_DIR , 'runtime.json') ); NODE_CONFIG_PARSER = util.initParam('NODE_CONFIG_PARSER'); if (NODE_CONFIG_PARSER) { try { var parserModule = Path.isAbsolute(NODE_CONFIG_PARSER) ? NODE_CONFIG_PARSER : Path.join(CONFIG_DIR, NODE_CONFIG_PARSER); Parser = require(parserModule); } catch (e) { console.warn('Failed to load config parser from ' + NODE_CONFIG_PARSER); console.log(e); } } // 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; if (!hostName) { var OS = require('os'); hostName = OS.hostname(); } } catch (e) { hostName = ''; } // Store the hostname that won. env.HOSTNAME = hostName; // Read each file in turn var baseNames = ['default'].concat(NODE_ENV); // #236: Also add full hostname when they are different. if (hostName) { var firstDomain = hostName.split('.')[0]; NODE_ENV.forEach(function(env) { // Backward compatibility baseNames.push(firstDomain, firstDomain + '-' + env); // Add full hostname when it is not the same if (hostName !== firstDomain) { baseNames.push(hostName, hostName + '-' + env); } }); } NODE_ENV.forEach(function(env) { baseNames.push('local', 'local-' + env); }); var allowedFiles = {}; var resolutionIndex = 1; var extNames = Parser.getFilesOrder(); baseNames.forEach(function(baseName) { extNames.forEach(function(extName) { allowedFiles[baseName + '.' + extName] = resolutionIndex++; if (APP_INSTANCE) { allowedFiles[baseName + '-' + APP_INSTANCE + '.' + extName] = resolutionIndex++; } }); }); var locatedFiles = util.locateMatchingFiles(CONFIG_DIR, allowedFiles); locatedFiles.forEach(function(fullFilename) { var configObj = util.parseFile(fullFilename, options); if (configObj) { util.extendDeep(config, configObj); } }); // Override configurations from the $NODE_CONFIG environment variable // NODE_CONFIG only applies to the base config if (!configDir) { 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); var skipConfigSources = util.getOption(options,'skipConfigSources', false); if (!skipConfigSources){ 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); var skipConfigSources = util.getOption(options,'skipConfigSources', false); if (!skipConfigSources){ configSources.push({ name: "--NODE_CONFIG argument", parsed: cmdLineConfig, }); } } // Place the mixed NODE_CONFIG into the environment env['NODE_CONFIG'] = JSON.stringify(util.extendDeep(envConfig, 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); // 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; }; /** * Return a list of fullFilenames who exists in allowedFiles * Ordered according to allowedFiles argument specifications * * @protected * @method locateMatchingFiles * @param configDirs {string} the config dir, or multiple dirs separated by a column (:) * @param allowedFiles {object} an object. keys and supported filenames * and values are the position in the resolution order * @returns {string[]} fullFilenames - path + filename */ util.locateMatchingFiles = function(configDirs, allowedFiles) { return configDirs.split(Path.delimiter) .reduce(function(files, configDir) { if (configDir) { try { FileSystem.readdirSync(configDir).forEach(function(file) { if (allowedFiles[file]) { files.push([allowedFiles[file], Path.join(configDir, file)]); } }); } catch(e) {} return files; } }, []) .sort(function(a, b) { return a[0] - b[0]; }) .map(function(file) { return file[1]; }); }; // Using basic recursion pattern, find all the deferred values and resolve them. util.resolveDeferredConfigs = function (config) { var deferred = []; function _iterate (prop) { // We put the properties we are going to look it in an array to keep the order predictable var propsToSort = []; // First step is to put the properties of interest in an array for (var property in prop) { if (Object.hasOwnProperty.call(prop, property) && prop[property] != null) { propsToSort.push(property); } } // Second step is to iterate of the elements in a predictable (sorted) order propsToSort.sort().forEach(function (property) { if (prop[property].constructor === Object) { _iterate(prop[property]); } else if (prop[property].constructor === Array) { for (var i = 0; i < prop[property].length; i++) { if (prop[property][i] instanceof DeferredConfig) { deferred.push(prop[property][i].prepare(config, prop[property], i)); } else { _iterate(prop[property][i]); } } } else { if (prop[property] instanceof DeferredConfig) { deferred.push(prop[property].prepare(config, prop, property)); } // else: Nothing to do. Keep the property how it is. } }); } _iterate(config); deferred.forEach(function (defer) { defer.resolve(); }); }; /** * 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, xml) * 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 * @param options { object | undefined } parsing options. Current supported option: skipConfigSources: true|false * @return configObject {object|null} The configuration object parsed from the file */ util.parseFile = function(fullFilename, options) { var t = this, // Initialize configObject = null, fileContent = null, stat = null; // Note that all methods here are the Sync versions. This is appropriate during // module loading (which is a synchronous operation), but not thereafter. try { // Try loading the file. fileContent = FileSystem.readFileSync(fullFilename, 'utf-8'); fileContent = fileContent.replace(/^\uFEFF/, ''); } catch (e2) { if (e2.code !== 'ENOENT') { throw new Error('Config file ' + fullFilename + ' cannot be read. Error code is: '+e2.code +'. Error message is: '+e2.message); } return null; // file doesn't exists } // Parse the file based on extension try { // skip if it's a gitcrypt file and CONFIG_SKIP_GITCRYPT is true if (CONFIG_SKIP_GITCRYPT) { if (gitCryptTestRegex.test(fileContent)) { console.error('WARNING: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is set. skipping.'); return null; } } configObject = Parser.parse(fullFilename, fileContent); } catch (e3) { if (gitCryptTestRegex.test(fileContent)) { console.error('ERROR: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is not set.'); } throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3); } // Keep track of this configuration sources, including empty ones, unless the skipConfigSources flag is set to true in the options var skipConfigSources = util.getOption(options,'skipConfigSources', false); if (typeof configObject === 'object' && !skipConfigSources) { configSources.push({ name: fullFilename, original: fileContent, parsed: configObject, }); } return configObject; }; /** * Parse and return the specified 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 * xml = Parsed with a XML parser * * 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) { var parser = Parser.getParser(format); if (typeof parser === 'function') { return parser(null, content); } }; /** * Attach the Config class prototype to all config objects recursively. * ** This allows you to do anything with CONFIG sub-objects as you can do with * the top-level CONFIG object. It's so you can do this: *
* ** var CUST_CONFIG = require('config').Customer; * CUST_CONFIG.get(...) ** * @protected * @method attachProtoDeep * @param toObject * @param depth * @return toObject */ util.attachProtoDeep = function(toObject, depth) { if (toObject instanceof RawConfig) { return toObject; } // Recursion detection var t = this; depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); if (depth < 0) { return toObject; } // Adding Config.prototype methods directly to toObject as hidden properties // because adding to toObject.__proto__ exposes the function in toObject for (var fnName in Config.prototype) { if (!toObject[fnName]) { util.makeHidden(toObject, fnName, Config.prototype[fnName]); } } // Add prototypes to sub-objects for (var prop in toObject) { if (util.isObject(toObject[prop])) { util.attachProtoDeep(toObject[prop], depth - 1); } } // Return the original object return toObject; }; /** * Return a deep copy of the specified object. * * This returns a new object with all elements copied from the specified * object. Deep copies are made of objects and arrays so you can do anything * with the returned object without affecting the input object. * * @protected * @method cloneDeep * @param parent {object} The original object to copy from * @param [depth=20] {Integer} Maximum depth (default 20) * @return {object} A new object with the elements copied from the copyFrom object * * This method is copied from https://github.com/pvorb/node-clone/blob/17eea36140d61d97a9954c53417d0e04a00525d9/clone.js * * Copyright © 2011-2014 Paul Vorbach and contributors. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Softwareâ€), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: The above copyright notice and this permission * notice shall be included in all copies or substantial portions of the Software. */ util.cloneDeep = function cloneDeep(parent, depth, circular, prototype) { // maintain two arrays for circular references, where corresponding parents // and children have the same index var allParents = []; var allChildren = []; var useBuffer = typeof Buffer != 'undefined'; if (typeof circular === 'undefined') circular = true; if (typeof depth === 'undefined') depth = 20; // recurse this function so we don't reset allParents and allChildren function _clone(parent, depth) { // cloning null always returns null if (parent === null) return null; if (depth === 0) return parent; var child; if (typeof parent != 'object') { return parent; } if (Utils.isArray(parent)) { child = []; } else if (Utils.isRegExp(parent)) { child = new RegExp(parent.source, util.getRegExpFlags(parent)); if (parent.lastIndex) child.lastIndex = parent.lastIndex; } else if (Utils.isDate(parent)) { child = new Date(parent.getTime()); } else if (useBuffer && Buffer.isBuffer(parent)) { child = Buffer.alloc(parent.length); parent.copy(child); return child; } else { if (typeof prototype === 'undefined') child = Object.create(Object.getPrototypeOf(parent)); else child = Object.create(prototype); } if (circular) { var index = allParents.indexOf(parent); if (index != -1) { return allChildren[index]; } allParents.push(parent); allChildren.push(child); } for (var i in parent) { var propDescriptor = Object.getOwnPropertyDescriptor(parent,i); var hasGetter = ((propDescriptor !== undefined) && (propDescriptor.get !== undefined)); if (hasGetter){ Object.defineProperty(child,i,propDescriptor); } else if (util.isPromise(parent[i])) { child[i] = parent[i]; } else { child[i] = _clone(parent[i], depth - 1); } } return child; } return _clone(parent, depth); }; /** * Set objects given a path as a string list * * @protected * @method setPath * @param object {object} - Object to set the property on * @param path {array[string]} - Array path to the property * @param value {*} - value to set, ignoring null */ util.setPath = function (object, path, value) { var nextKey = null; if (value === null || path.length === 0) { return; } else if (path.length === 1) { // no more keys to make, so set the value object[path.shift()] = value; } else { nextKey = path.shift(); if (!Object.hasOwnProperty.call(object, nextKey)) { object[nextKey] = {}; } util.setPath(object[nextKey], path, value); } }; /** * Create a new object patterned after substitutionMap, where: * 1. Terminal string values in substitutionMap are used as keys * 2. To look up values in a key-value store, variables * 3. And parent keys are created as necessary to retain the structure of substitutionMap. * * @protected * @method substituteDeep * @param substitutionMap {object} - an object whose terminal (non-subobject) values are strings * @param variables {object[string:value]} - usually process.env, a flat object used to transform * terminal values in a copy of substitutionMap. * @returns {object} - deep copy of substitutionMap with only those paths whose terminal values * corresponded to a key in `variables` */ util.substituteDeep = function (substitutionMap, variables) { var result = {}; function _substituteVars(map, vars, pathTo) { for (var prop in map) { var value = map[prop]; if (typeof(value) === 'string') { // We found a leaf variable name if (vars[value] !== undefined && vars[value] !== '') { // if the vars provide a value set the value in the result map util.setPath(result, pathTo.concat(prop), vars[value]); } } else if (util.isObject(value)) { // work on the subtree, giving it a clone of the pathTo if ('__name' in value && '__format' in value && vars[value.__name] !== undefined && vars[value.__name] !== '') { try { var parsedValue = util.parseString(vars[value.__name], value.__format); } catch(err) { err.message = '__format parser error in ' + value.__name + ': ' + err.message; throw err; } util.setPath(result, pathTo.concat(prop), parsedValue); } else { _substituteVars(value, vars, pathTo.concat(prop)); } } else { msg = "Illegal key type for substitution map at " + pathTo.join('.') + ': ' + typeof(value); throw Error(msg); } } } _substituteVars(substitutionMap, variables, []); return result; }; /* Map environment variables into the configuration if a mapping file, * `custom-environment-variables.EXT` exists. * * @protected * @method getCustomEnvVars * @param CONFIG_DIR {string} - the passed configuration directory * @param extNames {Array[string]} - acceptable configuration file extension names. * @returns {object} - mapped environment variables or {} if there are none */ util.getCustomEnvVars = function (CONFIG_DIR, extNames) { var result = {}; var resolutionIndex = 1; var allowedFiles = {}; extNames.forEach(function (extName) { allowedFiles['custom-environment-variables' + '.' + extName] = resolutionIndex++; }); var locatedFiles = util.locateMatchingFiles(CONFIG_DIR, allowedFiles); locatedFiles.forEach(function (fullFilename) { var configObj = util.parseFile(fullFilename); if (configObj) { var environmentSubstitutions = util.substituteDeep(configObj, process.env); util.extendDeep(result, environmentSubstitutions); } }); return result; }; /** * Return true if two objects have equal contents. * * @protected * @method equalsDeep * @param object1 {object} The object to compare from * @param object2 {object} The object to compare with * @param depth {integer} An optional depth to prevent recursion. Default: 20. * @return {boolean} True if both objects have equivalent contents */ util.equalsDeep = function(object1, object2, depth) { // Recursion detection var t = this; depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); if (depth < 0) { return {}; } // Fast comparisons if (!object1 || !object2) { return false; } if (object1 === object2) { return true; } if (typeof(object1) != 'object' || typeof(object2) != 'object') { return false; } // They must have the same keys. If their length isn't the same // then they're not equal. If the keys aren't the same, the value // comparisons will fail. if (Object.keys(object1).length != Object.keys(object2).length) { return false; } // Compare the values for (var prop in object1) { // Call recursively if an object or array if (object1[prop] && typeof(object1[prop]) === 'object') { if (!util.equalsDeep(object1[prop], object2[prop], depth - 1)) { return false; } } else { if (object1[prop] !== object2[prop]) { return false; } } } // Test passed. return true; }; /** * Returns an object containing all elements that differ between two objects. *
* This method was designed to be used to create the runtime.json file * contents, but can be used to get the diffs between any two Javascript objects. *
** It works best when object2 originated by deep copying object1, then * changes were made to object2, and you want an object that would give you * the changes made to object1 which resulted in object2. *
* * @protected * @method diffDeep * @param object1 {object} The base object to compare to * @param object2 {object} The object to compare with * @param depth {integer} An optional depth to prevent recursion. Default: 20. * @return {object} A differential object, which if extended onto object1 would * result in object2. */ util.diffDeep = function(object1, object2, depth) { // Recursion detection var t = this, diff = {}; depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); if (depth < 0) { return {}; } // Process each element from object2, adding any element that's different // from object 1. for (var parm in object2) { var value1 = object1[parm]; var value2 = object2[parm]; if (value1 && value2 && util.isObject(value2)) { if (!(util.equalsDeep(value1, value2))) { diff[parm] = util.diffDeep(value1, value2, depth - 1); } } else if (Array.isArray(value1) && Array.isArray(value2)) { if(!util.equalsDeep(value1, value2)) { diff[parm] = value2; } } else if (value1 !== value2){ diff[parm] = value2; } } // Return the diff object return diff; }; /** * Extend an object, and any object it contains. * * This does not replace deep objects, but dives into them * replacing individual elements instead. * * @protected * @method extendDeep * @param mergeInto {object} The object to merge into * @param mergeFrom... {object...} - Any number of objects to merge from * @param depth {integer} An optional depth to prevent recursion. Default: 20. * @return {object} The altered mergeInto object is returned */ util.extendDeep = function(mergeInto) { // Initialize var t = this; var vargs = Array.prototype.slice.call(arguments, 1); var depth = vargs.pop(); if (typeof(depth) != 'number') { vargs.push(depth); depth = DEFAULT_CLONE_DEPTH; } // Recursion detection if (depth < 0) { return mergeInto; } // Cycle through each object to extend vargs.forEach(function(mergeFrom) { // Cycle through each element of the object to merge from for (var prop in mergeFrom) { // save original value in deferred elements var fromIsDeferredFunc = mergeFrom[prop] instanceof DeferredConfig; var isDeferredFunc = mergeInto[prop] instanceof DeferredConfig; if (fromIsDeferredFunc && Object.hasOwnProperty.call(mergeInto, prop)) { mergeFrom[prop]._original = isDeferredFunc ? mergeInto[prop]._original : mergeInto[prop]; } // Extend recursively if both elements are objects and target is not really a deferred function if (mergeFrom[prop] instanceof Date) { mergeInto[prop] = mergeFrom[prop]; } if (mergeFrom[prop] instanceof RegExp) { mergeInto[prop] = mergeFrom[prop]; } else if (util.isObject(mergeInto[prop]) && util.isObject(mergeFrom[prop]) && !isDeferredFunc) { util.extendDeep(mergeInto[prop], mergeFrom[prop], depth - 1); } else if (util.isPromise(mergeFrom[prop])) { mergeInto[prop] = mergeFrom[prop]; } // Copy recursively if the mergeFrom element is an object (or array or fn) else if (mergeFrom[prop] && typeof mergeFrom[prop] === 'object') { mergeInto[prop] = util.cloneDeep(mergeFrom[prop], depth -1); } // Copy property descriptor otherwise, preserving accessors else if (Object.getOwnPropertyDescriptor(Object(mergeFrom), prop)){ Object.defineProperty(mergeInto, prop, Object.getOwnPropertyDescriptor(Object(mergeFrom), prop)); } else { mergeInto[prop] = mergeFrom[prop]; } } }); // Chain return mergeInto; }; /** * Is the specified argument a regular javascript object? * * The argument is an object if it's a JS object, but not an array. * * @protected * @method isObject * @param obj {*} An argument of any type. * @return {boolean} TRUE if the arg is an object, FALSE if not */ util.isObject = function(obj) { return (obj !== null) && (typeof obj === 'object') && !(Array.isArray(obj)); }; /** * Is the specified argument a javascript promise? * * @protected * @method isPromise * @param obj {*} An argument of any type. * @returns {boolean} */ util.isPromise = function(obj) { return Object.prototype.toString.call(obj) === '[object Promise]'; }; /** *Initialize a parameter from the command line or process environment
* ** This method looks for the parameter from the command line in the format * --PARAMETER=VALUE, then from the process environment, then from the * default specified as an argument. *
* * @method initParam * @param paramName {String} Name of the parameter * @param [defaultValue] {Any} Default value of the parameter * @return {Any} The found value, or default value */ util.initParam = function (paramName, defaultValue) { var t = this; // Record and return the value var value = util.getCmdLineArg(paramName) || process.env[paramName] || defaultValue; env[paramName] = value; return value; } /** *Get Command Line Arguments
* ** This method allows you to retrieve the value of the specified command line argument. *
* ** The argument is case sensitive, and must be of the form '--ARG_NAME=value' *
* * @method getCmdLineArg * @param searchFor {String} The argument name to search for * @return {*} false if the argument was not found, the argument value if found */ util.getCmdLineArg = function (searchFor) { var cmdLineArgs = process.argv.slice(2, process.argv.length), argName = '--' + searchFor + '='; for (var argvIt = 0; argvIt < cmdLineArgs.length; argvIt++) { if (cmdLineArgs[argvIt].indexOf(argName) === 0) { return cmdLineArgs[argvIt].substr(argName.length); } } return false; } /** *Get a Config Environment Variable Value
* ** This method returns the value of the specified config environment variable, * including any defaults or overrides. *
* * @method getEnv * @param varName {String} The environment variable name * @return {String} The value of the environment variable */ util.getEnv = function (varName) { return env[varName]; } /** * Returns a string of flags for regular expression `re`. * * @param {RegExp} re Regular expression * @returns {string} Flags */ util.getRegExpFlags = function (re) { var flags = ''; re.global && (flags += 'g'); re.ignoreCase && (flags += 'i'); re.multiline && (flags += 'm'); return flags; }; /** * Returns a new deep copy of the current config object, or any part of the config if provided. * * @param {Object} config The part of the config to copy and serialize. Omit this argument to return the entire config. * @returns {Object} The cloned config or part of the config */ util.toObject = function(config) { return JSON.parse(JSON.stringify(config || this)); }; // Run strictness checks on NODE_ENV and NODE_APP_INSTANCE and throw an error if there's a problem. util.runStrictnessChecks = function (config) { var sources = config.util.getConfigSources(); var sourceFilenames = sources.map(function (src) { return Path.basename(src.name); }); NODE_ENV.forEach(function(env) { // Throw an exception if there's no explicit config file for NODE_ENV var anyFilesMatchEnv = sourceFilenames.some(function (filename) { return filename.match(env); }); // development is special-cased because it's the default value if (env && (env !== 'development') && !anyFilesMatchEnv) { _warnOrThrow(NODE_ENV_VAR_NAME+" value of '"+env+"' did not match any deployment config file names."); } // Throw if NODE_ENV matches' default' or 'local' if ((env === 'default') || (env === 'local')) { _warnOrThrow(NODE_ENV_VAR_NAME+" value of '"+env+"' is ambiguous."); } }); // Throw an exception if there's no explicit config file for NODE_APP_INSTANCE var anyFilesMatchInstance = sourceFilenames.some(function (filename) { return filename.match(APP_INSTANCE); }); if (APP_INSTANCE && !anyFilesMatchInstance) { _warnOrThrow("NODE_APP_INSTANCE value of '"+APP_INSTANCE+"' did not match any instance config file names."); } function _warnOrThrow (msg) { var beStrict = process.env.NODE_CONFIG_STRICT_MODE; var prefix = beStrict ? 'FATAL: ' : 'WARNING: '; var seeURL = 'See https://github.com/lorenwest/node-config/wiki/Strict-Mode'; console.error(prefix+msg); console.error(prefix+seeURL); // Accept 1 and true as truthy values. When set via process.env, Node.js casts them to strings. if (["true", "1"].indexOf(beStrict) >= 0) { throw new Error(prefix+msg+' '+seeURL); } } }; // Instantiate and export the configuration var config = module.exports = new Config(); // copy methods to util for backwards compatibility util.stripComments = Parser.stripComments; util.stripYamlComments = Parser.stripYamlComments; // Produce warnings if the configuration is empty var showWarnings = !(util.initParam('SUPPRESS_NO_CONFIG_WARNING')); if (showWarnings && Object.keys(config).length === 0) { console.error('WARNING: No configurations found in configuration directory:' +CONFIG_DIR); console.error('WARNING: To disable this warning set SUPPRESS_NO_CONFIG_WARNING in the environment.'); } node-config-3.3.7/package.json 0000664 0000000 0000000 00000002205 14134613066 0016205 0 ustar 00root root 0000000 0000000 { "name": "config", "version": "3.3.6", "main": "./lib/config.js", "description": "Configuration control for production node deployments", "author": "Loren WestUnit tests
* * @module test */ var requireUncached = require('./_utils/requireUncached'); var vows = require('vows'); var assert = require('assert'); // Make a copy of the command line args var argvOrg = process.argv; /** *Tests for underlying node-config utilities. To run type:
*npm test*
Or, in a project that uses node-config:
*npm test config* * @class ProtectedTest */ var CONFIG; vows.describe('Protected (hackable) utilities test') .addBatch({ // We initialize the object in a batch so that the globals get changed at /run-time/ not /require-time/, // avoiding conflicts with other tests. // We initialize in our own /batch/ because batches are run in serial, while individual contexts run in parallel. 'Library initialization': { topic : function () { // Change the configuration directory for testing process.env.NODE_CONFIG_DIR = __dirname + '/config'; // Hard-code $NODE_ENV=test for testing process.env.NODE_ENV='test'; // Test for multi-instance applications process.env.NODE_APP_INSTANCE='3'; // Test $NODE_CONFIG environment and --NODE_CONFIG command line parameter process.env.NODE_CONFIG='{"EnvOverride":{"parm3":"overridden from $NODE_CONFIG","parm4":100}}'; process.argv.push('--NODE_CONFIG={"EnvOverride":{"parm5":"overridden from --NODE_CONFIG","parm6":101}}'); // Test Environment Variable Substitution var override = 'CUSTOM VALUE FROM JSON ENV MAPPING'; process.env['CUSTOM_JSON_ENVIRONMENT_VAR'] = override; // Dependencies CONFIG = requireUncached(__dirname + '/../lib/config'); return CONFIG; }, 'Library is available': function(config) { assert.isObject(config); } } }) .addBatch({ 'isObject() tests': { 'The function exists': function() { assert.isFunction(CONFIG.util.isObject); }, 'Correctly identifies objects': function() { assert.isTrue(CONFIG.util.isObject({A:"b"})); }, 'Correctly excludes non-objects': function() { assert.isFalse(CONFIG.util.isObject("some string")); assert.isFalse(CONFIG.util.isObject(45)); assert.isFalse(CONFIG.util.isObject([2, 3])); assert.isFalse(CONFIG.util.isObject(["a", "b"])); assert.isFalse(CONFIG.util.isObject(null)); assert.isFalse(CONFIG.util.isObject(undefined)); } }, '_cloneDeep() tests': { topic: function() { // Return an object for copy tests return { elem0:true, elem1:"Element 1", elem2:2, elem3:[1,2,3], elem4:function(){return "hello";}, elem5:{sub1:"sub 1",sub2:2,sub3:[1,2,3]}, elem6: {date: new Date, regexp: /test/i} }; }, 'The function exists': function() { assert.isFunction(CONFIG.util.cloneDeep); }, 'Original and copy should test equivalent (deep)': function(orig) { var copy = CONFIG.util.cloneDeep(orig); assert.deepEqual(copy, orig); }, 'The objects should be different': function(orig) { var copy = CONFIG.util.cloneDeep(orig); copy.elem1 = false; assert.notDeepEqual(copy, orig); }, 'Object clones should be objects': function(orig) { assert.isObject(CONFIG.util.cloneDeep({a:1, b:2})); }, 'Array clones should be arrays': function(orig) { assert.isArray(CONFIG.util.cloneDeep(["a", "b", 3])); }, 'Arrays should be copied by value, not by reference': function(orig) { var copy = CONFIG.util.cloneDeep(orig); assert.deepEqual(copy, orig); copy.elem3[0] = 2; // If the copy wasn't deep, elem3 would be the same object assert.notDeepEqual(copy, orig); }, 'Objects should be copied by value, not by reference': function(orig) { var copy = CONFIG.util.cloneDeep(orig); copy.elem5.sub2 = 3; assert.notDeepEqual(copy, orig); copy = CONFIG.util.cloneDeep(orig); copy.elem5.sub3[1] = 3; assert.notDeepEqual(copy, orig); }, 'Regexps and dates are preserved': function (orig) { var copy = CONFIG.util.cloneDeep(orig); assert.equal(copy.elem6.date.constructor.name, 'Date'); assert.equal(copy.elem6.regexp.toString(), '/test/i'); } }, 'extendDeep() tests': { 'The function exists': function() { assert.isFunction(CONFIG.util.extendDeep); }, 'Performs normal extend': function() { var orig = {elem1:"val1", elem2:"val2"}; var extWith = {elem3:"val3"}; var shouldBe = {elem1:"val1", elem2:"val2", elem3:"val3"}; assert.deepEqual(CONFIG.util.extendDeep(orig, extWith), shouldBe); }, 'Replaces non-objects': function() { var orig = {elem1:"val1", elem2:["val2","val3"],elem3:{sub1:"val4"}}; var extWith = {elem1:1,elem2:["val4"],elem3:"val3"}; var shouldBe = {elem1:1, elem2:["val4"],elem3:"val3"}; assert.deepEqual(CONFIG.util.extendDeep(orig, extWith), shouldBe); }, 'Merges objects': function() { var orig = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; var extWith = {elem2:{sub2:"val6",sub3:"val7"}}; var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val6",sub3:"val7"}}; assert.deepEqual(CONFIG.util.extendDeep(orig, extWith), shouldBe); }, 'Merges dates': function() { var orig = {e1:"val1", elem2:{sub1:"val4",sub2:new Date(2015, 0, 1)}}; var extWith = {elem2:{sub2:new Date(2015, 0, 2),sub3:"val7"}}; var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:new Date(2015, 0, 2),sub3:"val7"}}; assert.deepEqual(CONFIG.util.extendDeep(orig, extWith), shouldBe); }, 'Creates partial objects when mixing objects and non-objects': function () { var orig = {elem1: {sub1: 5}}; var ext1 = {elem1: {sub2: 7}}; var ext2 = {elem1: 7}; var ext3 = {elem1: {sub3: 13}}; // When we get to ext2, the 7 clears all memories of sub1 and sub3. Then, when // we merge with ext3, the 7 is replaced by the new object. var expected = {elem1: {sub3: 13}}; assert.deepEqual(CONFIG.util.extendDeep(orig, ext1, ext2, ext3), expected); }, 'Correctly types new objects and arrays': function() { var orig = {e1:"val1", e3:["val5"]}; var extWith = {e2:{elem1:"val1"}, e3:["val6","val7"]}; var shouldBe = {e1:"val1", e2:{elem1:"val1"}, e3:["val6","val7"]}; var ext = CONFIG.util.extendDeep({}, orig, extWith); assert.isObject(ext.e2); assert.isArray(ext.e3); assert.deepEqual(ext, shouldBe); }, 'Keeps non-merged objects intact': function() { var orig = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; var extWith = {elem3:{sub2:"val6",sub3:"val7"}}; CONFIG.util.extendDeep({}, orig, extWith); assert.deepEqual(orig, shouldBe); }, 'Keeps prototype methods intact': function() { var orig = Object.create({has: function() {}}); var result = CONFIG.util.extendDeep({}, orig, {}); assert.isFunction(result.has); } }, 'equalsDeep() tests': { 'The function exists': function() { assert.isFunction(CONFIG.util.equalsDeep); }, 'Succeeds on two empty objects': function() { assert.isTrue(CONFIG.util.equalsDeep({}, {})); }, 'Succeeds on array comparisons': function() { assert.isTrue(CONFIG.util.equalsDeep([1,'hello',2], [1,'hello',2])); }, 'Succeeds on the same object': function() { var a = {hello:'world'}; assert.isTrue(CONFIG.util.equalsDeep(a, a)); }, 'Succeeds on a regular object': function() { var a = {value_3: 14, hello:'world', value_1: 29}; var b = {value_1: 29, hello:'world', value_3: 14}; assert.isTrue(CONFIG.util.equalsDeep(a, b)); }, 'Succeeds on a deep object': function() { var a = {value_3: 14, hello:'world', value_1: 29, value_4:['now','is','the','time']}; var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; var c = {creditLimit: 10000, deepValue: a}; var d = {deepValue: b, creditLimit:10000}; assert.isTrue(CONFIG.util.equalsDeep(c, d)); }, 'Fails if either object is null': function() { assert.isFalse(CONFIG.util.equalsDeep({}, null)); assert.isFalse(CONFIG.util.equalsDeep(null, {})); assert.isFalse(CONFIG.util.equalsDeep(null, null)); }, 'Fails if either object is undefined': function() { var a = {}; assert.isFalse(CONFIG.util.equalsDeep({})); assert.isFalse(CONFIG.util.equalsDeep(a['noElement'], {})); }, 'Fails if either object is undefined': function() { var a = {}; assert.isFalse(CONFIG.util.equalsDeep({})); assert.isFalse(CONFIG.util.equalsDeep(a['noElement'], {})); }, 'Fails if object1 has more elements': function() { var a = {value_3: 14, hello:'world', value_1: 29, otherElem: 40}; var b = {value_1: 29, hello:'world', value_3: 14}; assert.isFalse(CONFIG.util.equalsDeep(a, b)); }, 'Fails if object2 has more elements': function() { var a = {value_1: 29, hello:'world', value_3: 14}; var b = {value_3: 14, hello:'world', value_1: 29, otherElem: 40}; assert.isFalse(CONFIG.util.equalsDeep(a, b)); }, 'Fails if any value is different': function() { var a = {value_1: 30, hello:'world', value_3: 14, value_4:['now','is','the','time']}; var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; assert.isFalse(CONFIG.util.equalsDeep(a, b)); var a = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','isnt','the','time']}; assert.isFalse(CONFIG.util.equalsDeep(a, b)); } }, 'diffDeep() tests': { 'The function exists': function() { assert.isFunction(CONFIG.util.diffDeep); }, 'Returns an empty object if no differences': function() { var a = {value_3: 14, hello:'world', value_1: 29}; var b = {value_1: 29, hello:'world', value_3: 14}; assert.equal(typeof(CONFIG.util.diffDeep(a,b)), 'object'); assert.isTrue(Object.keys(CONFIG.util.diffDeep(a, b)).length == 0); }, 'Returns an empty object if no differences (deep)': function() { var a = {value_3: 14, hello:'world', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}}; var b = {value_1: 29, hello:'world', value_3: 14, value_4:[1,'hello',2], deepObj:{a:22,b:{a:44,c:45}}}; assert.equal(typeof(CONFIG.util.diffDeep(a,b)), 'object'); assert.isTrue(Object.keys(CONFIG.util.diffDeep(a, b)).length == 0); }, 'Returns just the diff values': function() { var a = {value_3: 14, hello:'wurld', value_1: 29, deepObj:{a:22,b:{c:45,a:44}}}; var b = {value_1: 29, hello:'world', value_3: 14, deepObj:{a:22,b:{a:44,c:45}}}; var diff = CONFIG.util.diffDeep(a,b); assert.equal(Object.keys(diff).length, 1); assert.equal(diff.hello, 'world'); }, 'Returns just the diff values (deep)': function() { var a = {value_3: 14, hello:'wurld', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}}; var b = {value_1: 29, hello:'wurld', value_3: 14, value_4:[1,'goodbye',2], deepObj:{a:22,b:{a:45,c:44}}}; var diff = CONFIG.util.diffDeep(a,b); assert.equal(Object.keys(diff).length, 2); assert.equal(Object.keys(diff.deepObj).length, 1); assert.equal(Object.keys(diff.deepObj.b).length, 2); assert.equal(diff.deepObj.b.a, 45); assert.equal(diff.deepObj.b.c, 44); assert.deepEqual(diff.value_4, [1, 'goodbye', 2]); } }, 'substituteDeep() tests': { topic: function () { var topic = { TopLevel: 'SOME_TOP_LEVEL', TestModule: { parm1: "SINGLE_SECOND_LEVEL" }, Customers: { dbHost: 'DB_HOST', dbName: 'DB_NAME', oauth: { key: 'OAUTH_KEY', secret: 'OAUTH_SECRET' } } }; return topic; }, 'returns an empty object if the variables mapping is empty': function (topic) { vars = {}; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, {}); }, 'returns an empty object if none of the variables map to leaf strings': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, {}); }, 'returns an object with keys matching down to mapped existing variables': function (topic) { vars = { 'SOME_TOP_LEVEL': 5, 'DB_NAME': 'production_db', 'OAUTH_SECRET': '123456', 'PATH': 'ignore other environment variables' }; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { TopLevel: 5, Customers: { dbName: 'production_db', oauth: { secret: '123456' } } }); }, 'Returns an object with keys matching down to mapped existing and defined variables': function (topic) { vars = { 'SOME_TOP_LEVEL': 0, 'DB_HOST': undefined, 'DB_NAME': '', 'OAUTH_SECRET': 'false', 'OAUTH_KEY': 'null', 'PATH': '' }; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { TopLevel: 0, Customers: { oauth: { key: 'null', secret: 'false' } } }); }, 'returns an object with keys matching down to mapped existing variables with JSON content': function (topic) { vars = { 'DB_HOST': '{"port":"3306","host":"example.com"}' }; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { Customers: { dbHost: '{"port":"3306","host":"example.com"}' } }); }, 'Returns an object with keys matching down to mapped existing and defined variables with JSON content': function (topic) { var dbHostObject = { param1WithZero: 0, param2WithFalse: false, param3WithNull: null, param4WithEmptyObject: {}, param5WithEmptyArray: [], param6WithEmptyString: '' }; var dbHostObjectWithUndefinedProperty = Object.assign({}, dbHostObject, { param7WithUndefined: undefined }); vars = { 'DB_HOST': JSON.stringify(dbHostObjectWithUndefinedProperty) }; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { Customers: { dbHost: JSON.stringify(dbHostObject) } }); }, 'returns an object with keys matching down to mapped and JSON-parsed existing variables': function (topic) { vars = { 'DB_HOST': '{"port":"3306","host":"example.com"}' }; topic.Customers.dbHost = {__name: 'DB_HOST', __format: 'json'}; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { Customers: { dbHost: { port: '3306', host: 'example.com' } } }); }, 'Returns an object with keys matching down to mapped and JSON-parsed existing and defined variables': function (topic) { var dbHostObject = { param1WithZero: 0, param2WithFalse: false, param3WithNull: null, param4WithEmptyObject: {}, param5WithEmptyArray: [], param6WithEmptyString: '' }; var dbHostObjectWithUndefinedProperty = Object.assign({}, dbHostObject, { param7WithUndefined: undefined }); vars = { 'DB_HOST': JSON.stringify(dbHostObjectWithUndefinedProperty) }; topic.Customers.dbHost = {__name: 'DB_HOST', __format: 'json'}; var substituted = CONFIG.util.substituteDeep(topic, vars); assert.deepEqual(substituted, { Customers: { dbHost: dbHostObject } }); }, // Testing all the things in variable maps that don't make sense because ENV vars are always // strings. 'Throws an error for leaf Array values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = ['a', 'b', 'c']; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error for leaf Boolean values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = false; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error for leaf Numeric values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = 443; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error for leaf null values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = null; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error for leaf Undefined values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = undefined; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error for leaf NaN values': function (topic) { vars = { NON_EXISTENT_VAR: 'ignore_this' }; topic.Customers.dbHost = NaN; assert.throws(function () { CONFIG.util.substituteDeep(topic, vars); }); }, 'Throws an error with message describing variables name that throw a parser error': function(topic) { var JSON_WITH_SYNTAX_ERROR = '{"port":"3306","host" "example.com"}' vars = { 'DB_HOST': JSON_WITH_SYNTAX_ERROR }; topic.Customers.dbHost = {__name: 'DB_HOST', __format: 'json'}; try { CONFIG.util.substituteDeep(topic, vars); assert.isTrue(false); } catch(err) { assert.match(err.message, /__format parser error in DB_HOST: /); } } }, 'setPath() tests:': { topic: function () { return { TestModule: { parm1: "value1" }, Customers: { dbHost: 'base', dbName: 'from_default_js', oauth: { key: 'a_api_key', secret: 'an_api_secret' } }, EnvOverride: { parm_number_1: "from_default_js", parm2: 22 } }; }, 'Ignores null values': function (topic) { CONFIG.util.setPath(topic, ['Customers', 'oauth', 'secret'], null); assert.equal(topic.Customers.oauth.secret, 'an_api_secret'); }, 'Creates top-level keys to set new values': function (topic) { CONFIG.util.setPath(topic, ['NewKey'], 'NEW_VALUE'); assert.equal(topic.NewKey, 'NEW_VALUE'); }, 'Creates sub-keys to set new values': function (topic) { CONFIG.util.setPath(topic, ['TestModule', 'oauth'], 'NEW_VALUE'); assert.equal(topic.TestModule.oauth, 'NEW_VALUE'); }, 'Creates parents to set new values': function (topic) { CONFIG.util.setPath(topic, ['EnvOverride', 'oauth', 'secret'], 'NEW_VALUE'); assert.equal(topic.EnvOverride.oauth.secret, 'NEW_VALUE'); }, 'Overwrites existing values': function (topic) { CONFIG.util.setPath(topic, ['Customers'], 'NEW_VALUE'); assert.equal(topic.Customers, 'NEW_VALUE'); } }, 'stripComments() tests': { // Only testing baseline stripComments functionality. // This implementation handles lots of edge cases that aren't in these tests 'The function exists': function() { assert.isFunction(CONFIG.util.stripComments); }, 'Leaves a simple string without comments alone': function() { var str = "Hello\nWorld"; assert.equal(CONFIG.util.stripComments(str), str); }, 'Strips out line-type comments': function() { var str1 = "var a='Hello'; // Comment about the a variable"; var str2 = "var a='Hello'; "; assert.equal(CONFIG.util.stripComments(str1), str2); }, 'Strips out block-type comments': function() { var str1 = "var a='Hello';/* Block Comment */ var b=24"; var str2 = "var a='Hello'; var b=24"; assert.equal(CONFIG.util.stripComments(str1), str2); }, 'Strips out multi-line block comments': function() { var str1 = "var a='Hello';\n/* Block Comment\n Line 2 comment\n*/\nvar b=24"; var str2 = "var a='Hello';\n\nvar b=24"; assert.equal(CONFIG.util.stripComments(str1), str2); } }, 'parseFile() tests': { topic: function() { return CONFIG.util.parseFile(__dirname + '/config/default.yaml'); }, 'The function exists': function() { assert.isFunction(CONFIG.util.parseFile); }, 'An object is returned': function(config) { assert.isObject(config); }, 'The correct object is returned': function(config) { assert.isObject(config.Customers); assert.isTrue(config.Customers.dbName == 'from_default_yaml'); assert.isTrue(config.Customers.dbPort == 5984); assert.isObject(config.AnotherModule); assert.isTrue(config.AnotherModule.parm2 == "value2"); } }, 'CSON parse tests': { topic: function() { return CONFIG.util.parseFile(__dirname + '/config/default.cson'); }, 'The function exists': function() { assert.isFunction(CONFIG.util.parseFile); }, 'An object is returned': function(config) { assert.isObject(config); }, 'The correct object is returned': function(config) { assert.isObject(config.Customers); assert.isTrue(config.Customers.dbName == 'from_default_cson'); assert.isTrue(config.Customers.dbPassword == 'password will be overwritten.'); assert.isObject(config.AnotherModule); assert.isTrue(config.AnotherModule.parm4 == "value4"); assert.isArray(config.Customers.lang); } }, '.properties parse tests': { topic: function() { return CONFIG.util.parseFile(__dirname + '/config/default.properties'); }, 'The function exists': function() { assert.isFunction(CONFIG.util.parseFile); }, 'An object is returned': function(config) { assert.isObject(config); }, 'The correct object is returned': function(config) { assert.isObject(config.AnotherModule); assert.isTrue(config.AnotherModule.parm5 == "value5"); assert.isObject(config['key with spaces']); assert.isTrue(config['key with spaces'].another_key == 'hello'); assert.isUndefined(config.ignore_this_please); assert.isUndefined(config.i_am_a_comment); }, 'Variable replacements are working': function(config) { assert.isTrue(config.replacement.param == "foobar") }, 'Sections are supported': function(config) { assert.isDefined(config.section.param); assert.isUndefined(config.param); } }, 'loadFileConfigs() tests': { topic: function() { return CONFIG.util.loadFileConfigs(); }, 'The function exists': function() { assert.isFunction(CONFIG.util.loadFileConfigs); }, 'An object is returned': function(configs) { assert.isObject(configs); }, 'The correct object is returned': function(config) { assert.isObject(config.Customers); assert.isTrue(config.Customers.dbHost == 'base'); assert.isTrue(config.Customers.dbName == 'override_from_runtime_json'); } }, 'attachProtoDeep() tests': { topic: function() { // Create an object that contains other objects to see // that the prototype is added to all objects. var watchThis = { subObject: { item1: 23, subSubObject: { item2: "hello" } } }; return CONFIG.util.attachProtoDeep(watchThis); }, 'The function exists': function() { assert.isFunction(CONFIG.util.attachProtoDeep); }, 'The original object is returned': function(config) { assert.isObject(config); assert.isTrue(config.subObject.item1 === 23); assert.isTrue(config.subObject.subSubObject.item2 === "hello"); }, 'The cloneDeep method is attached to the object': function(config) { assert.isTrue({a:27}.a == config.util.cloneDeep({a:27}).a); }, 'The cloneDeep method is also attached to sub-objects': function(config) { assert.isTrue({a:27}.a == config.subObject.util.cloneDeep({a:27}).a); assert.isTrue({a:27}.a == config.subObject.subSubObject.util.cloneDeep({a:27}).a); }, 'Prototype methods are not exposed in the object': function(config) { // This test is here because altering object.__proto__ places the method // directly onto the object. That caused problems when iterating over the // object. This implementation does the same thing, but hides them. assert.isTrue(JSON.stringify(config) == '{"subObject":{"item1":23,"subSubObject":{"item2":"hello"}}}'); } }, 'getCmdLineArg() tests': { topic: function() { // Set process.argv example object var testArgv = [ process.argv[0], process.argv[1], '--NODE_ENV=staging' ]; process.argv = testArgv; return CONFIG.util.getCmdLineArg('NODE_ENV'); }, 'The function exists': function() { assert.isFunction(CONFIG.util.getCmdLineArg); }, 'NODE_ENV should be staging': function(nodeEnv) { assert.equal(nodeEnv, 'staging'); }, 'Returns false if the argument did not match': function() { assert.isFalse(CONFIG.util.getCmdLineArg('NODE_CONFIG_DIR')); }, 'Returns the argument (alternative syntax)': function() { process.argv.push('--NODE_CONFIG_DIR=/etc/nodeConfig'); assert.equal(CONFIG.util.getCmdLineArg('NODE_CONFIG_DIR'), '/etc/nodeConfig'); }, 'Returns always the first matching': function() { process.argv.push('--NODE_ENV=test'); assert.equal(CONFIG.util.getCmdLineArg('NODE_ENV'), 'staging'); }, 'Revert original process arguments': function() { assert.notEqual(process.argv, argvOrg); process.argv = argvOrg; assert.equal(process.argv, argvOrg); } }, 'toObject() tests': { topic: function() { return CONFIG.util.loadFileConfigs(); }, 'The function exists': function() { assert.isFunction(CONFIG.util.toObject); }, 'Returns a serialized version of the current instance if no argument is provided': function() { assert.notDeepStrictEqual(CONFIG.util.toObject(), CONFIG); }, 'Returns a POJO': function() { assert.ok(!(CONFIG.util.toObject() instanceof CONFIG.constructor)); }, 'Returns a serialized version of whatever argument is provided': function() { assert.notDeepStrictEqual(CONFIG.get('Customers'), { dbHost: 'base', dbName: 'override_from_runtime_json', dbPort: 5999, dbString: 'override_from_runtime_json:5999', random: 0.08624527123827352, dbPassword: 'real password', dbPassword2: 'another password', lang: ['en','de','es'], altDbPort: 4400, altDbPort1: 2209, emptySub: null }); } } }) .export(module); node-config-3.3.7/test/10-config/ 0000775 0000000 0000000 00000000000 14134613066 0016362 5 ustar 00root root 0000000 0000000 node-config-3.3.7/test/10-config/default.json 0000664 0000000 0000000 00000000615 14134613066 0020703 0 ustar 00root root 0000000 0000000 { "Customers": { "dbName":"from_default_json", "dbPassword":"password will be overwritten.", "lang":["en","es"] }, "AnotherModule": { "parm1":"value1" }, "staticArray": [2,1,3], "Inline": {"a": "", "b": "1"}, "ContainsQuote": "\"this has a quote\"", "MoreComplexQuote": "Test String" } node-config-3.3.7/test/10-config/encrypted.json 0000664 0000000 0000000 00000000120 14134613066 0021243 0 ustar 00root root 0000000 0000000 GITCRYPT ùEc¢…P?T§ÅD”ðû@šÏ•·>ÏäXHì›ê¤ÿ ‚µ(T¦^ÃBÅnì¾e&,ßj•'râªVóª'ŸÅÂB node-config-3.3.7/test/10-config/git-crypt-symmetric-key 0000664 0000000 0000000 00000000224 14134613066 0023025 0 ustar 00root root 0000000 0000000 GITCRYPTKEY LçB>úuÂåŠà’¹É=i{@±Ïur/¼²RQªÍ @×3žnå%|K}äƒÁ¢w¾r®C€Ú3ÌGÁp\óAÚ¶+7xL/ª-òSþ…Z[Ón lEP`ùpjŠª&