Giter Club home page Giter Club logo

node-config's Introduction

Configure your Node.js Applications

NPM   Build Status   release notes

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 within your application, and can be overridden and extended by environment variables, command line parameters, or external sources.

This gives your application a consistent configuration interface shared among a growing list of npm modules 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.

Install in your app directory, and edit the default config file.

$ npm install config
$ mkdir config
$ vi config/default.json
{
  // 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:

 $ vi config/production.json
{
  "Customer": {
    "dbConfig": {
      "host": "prod-db-server"
    },
    "credit": {
      "initialDays": 30
    }
  }
}

Use configs in your code:

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:

$ 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

Further Information

If you still don't see what you are looking for, here are some more resources to check:

Contributors

lorenwest markstos iMoses elliotttf jfelege leachiM2k
josx enyo leosuncin arthanzel eheikes th507
Osterjour cunneen nsabovic BadgerBadgerBadgerBadger simon-scherzinger leonardovillela
axelhzf benkroeger fgheorghe IvanVergiliev jpwilliams jaylynch
jberrisch kgoerlitz bertho-zero NguyenMatthieu nitzan-shaked robertrossmann

License

May be freely distributed under the MIT license.

Copyright (c) 2010-2022 Loren West and other contributors

node-config's People

Contributors

airdrummingfool avatar arthanzel avatar badgerbadgerbadgerbadger avatar cunneen avatar deutscherdude avatar dsbert avatar eheikes avatar elliotttf avatar enyo avatar fgheorghe avatar imoses avatar inside avatar jacobemerick avatar jamashita avatar jdmarshall avatar jfelege avatar josx avatar leachim2k avatar leonardovillela avatar leosuncin avatar lorenwest avatar markstos avatar ncuillery avatar nsabovic avatar osterjour avatar patrickpilch avatar simon-scherzinger avatar th507 avatar wmertens avatar xadillax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-config's Issues

Require newer YAML version?

Hi there! First, thanks for your package, really makes configuration simple. However, it has "yaml": "0.1.x" in its package.json. js-yaml 0.2.2 was released some time ago, do you think you could adjust the package.json so that npm doesn't use the deprecated version by default? :)

Error: hash not properly dedented

I've got this error, dont know why but since I updated to the lasted (0.4.18) its throwing this error

Error: Cannot parse config file: '/path/to/my/app/config/default.yaml': Error: hash not properly dedented, near "f147d1a81b06c7ed8c25512ba"

The most strange thing its that it doesnt take the first char of the facebook secret (its a number) and the end of the string. My yaml looks like

Facebook:
  app:
    id:        xxxx
    secret:    xf147d1a81b06c7ed8c25512baxxxx
    scope:     email

NODE_CONFIG_DIR should only affect host specific configs

I think all but the host specific config files should ignore NODE_CONFIG_DIR. I view the non host specific config files as sane defaults set by the developer and that someone deploying your app should never touch them.

Then you can use NODE_CONFIG_DIR to point to wherever your own config files are. Especially in production where you want to easily save the config between upgrades.

Problem when the working directory is not the app directory

Hi,

I've a problem with the uptime app, related to the config module.

I'd like to run uptime as a service on my Ubuntu 12.04 server, but my problem is that I can't launch the app from anywhere on my server. It seems that I need to be in the uptime directory, otherwise I get this error:

$ /usr/local/bin/node /var/www/uptime/app.js
Cannot write runtime.json file Error: ENOENT, no such file or directory '/home/gregoire/config/runtime.json'

fs.js:837
    throw errnoException(errno, 'watch');
          ^
Error: watch ENOENT
    at errnoException (fs.js:806:11)
    at FSWatcher.start (fs.js:837:11)
    at Object.fs.watch (fs.js:861:11)
    at Config.watchForConfigFileChanges (/var/www/uptime/node_modules/config/lib/config.js:468:37)
    at /var/www/uptime/node_modules/config/lib/config.js:1089:20
    at Module._compile (module.js:420:14)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)

It searches "config/runtime.json" in the working directory instead of searching it in the application root directory.
Is it a behavior that you can fix?

Thanks.

PS: the issue on uptime's repo fzaninotto/uptime#123

Outdated vows in node_modules

Hi again! :)

Looking into the node-config tests, I noticed that npm test doesn't work for me. I'm running node.js 0.6.1and get an error like this:

% npm test          

> [email protected] test /home/fred/dev/node-config
> ./node_modules/vows/bin/vows test/*.js --spec


node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
    at Function. (module.js:376:11)
    at Object. (/home/fred/dev/node-config/node_modules/vows/bin/vows:37:8)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)
npm ERR! [email protected] test: `./node_modules/vows/bin/vows test/*.js --spec`
npm ERR! `sh "-c" "./node_modules/vows/bin/vows test/*.js --spec"` failed with 1
npm ERR! 
npm ERR! Failed at the [email protected] test script.
npm ERR! This is most likely a problem with the config package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ./node_modules/vows/bin/vows test/*.js --spec
npm ERR! You can get their info via:
npm ERR!     npm owner ls config
npm ERR! There is likely additional logging output above.
npm ERR! 
npm ERR! System Linux 3.1.1-1-ARCH
npm ERR! command "node" "/usr/bin/npm" "test"
npm ERR! cwd /home/fred/dev/node-config
npm ERR! node -v v0.6.1
npm ERR! npm -v 1.0.104
npm ERR! code ELIFECYCLE
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/fred/dev/node-config/npm-debug.log
npm not ok

The vows version in node_modules seems to be 0.5.8, which seems to cause these problems. I just rm -rfed node_modules and did npm install, which gave me vows 0.5.13, everything works then. :)

License confusion...

The README states the license is Apache License 2.0 but the LICENSE file appears to be an MIT license. Copyright info is also out of sync between these two files.

Support for .yml extension

The typical extension for YAML in a lot of other tools is .yml. Could you add support for this (along with .yaml). It took me a while to figure out why my default.yml file wasn't working.

Error parsing runtime.json

I get following error pretty regularly:

Error parsing /path/to/config/runtime.json [SyntaxError: Unexpected end of input]

I think the problem is that node-config tries to read the file when another instance is currently writing to it. Is this a known issue? Could there just be something wrong with my setup?

Local, untracked config files.

The current configuration file list is really great to configure apps on multiple deployments but it doesn't provide a functionality to use config files that aren't meant to be checked into the VCS and remain untracked.

Sometimes I have sensitive information in my configuration files (like passwords) that I don't want in my repository.

For now I'm using (hostname).EXT as a workaround for those configs. It would be great to put host specific configurations in there that I can checkin though.

So what I would propose, is to add local.*.EXT config files. The parse order would be:

  1. default.EXT
  2. (hostname).EXT
  3. (deployment).EXT
  4. (hostname)-(deployment).EXT
  5. local.EXT
  6. local-(deployment).EXT

This way you can override any configuration everywhere, without getting a VCS conflict.

If you agree, I could make the changes, and create a pull request.

support for Express.app.set/get and support for callbacks

I would like to have in my config not only values but also to be able to set more then params...

For example:

this.app.configure('development', function() {
self.app.use(express.errorHandler({
dumpExceptions : true,
showStack : true
}));
});

In this code I am setting for the development env to show Exceptions, and I dont have a way to set this in the node-config files, this mast be hardcodded in the code...

Is it possible to force a reload of the config?

I am writing a test for our various different configurations - to ensure that after all the different host/environment/etc configs are loaded and merged, we end up the final config we expect.

e.g.
_.each(configs, function(envConfig){
var actualConfig = require(envConfig);
var expectedConfig = readExpectedConfig(envConfig);
test.deepEqual(actualConfig, expectedConfig);
test.done();
})

(I'm manipulating environment variables to

However, I cant seem to load more than 1 config because of the singleton nature of it.
Is there a way to do it already?
If not, should we add one?

Allow a single file to contain multiple configuration environments

Are there any plans to support a single config file for multiple environments rather than the current functionality of having a separate file for each environment? I find working with a single config file much easier, rather than having 10-15 different files for each environment.

The file would have to include an additional level of hierarchy which would define the purpose of that section of the configuration (e.g. host specific).

Can't change nor redefine DEFAULT_CLONE_DEPTH (JSON)

Hi @lorenwest,

In my particular situation I've reached and passed the DEFAULT_CLONE_DEPTH limit... I don't think it's so bad to have that level of nesting.. I'm working on a highly-configurable application that uses the config settings for passing options to other different libraries that I do not own.

Actually with this number the JSON doesn't load completely.

I know that the performance can be affected, but I wan't to assume the risk. In my case the application doesn't need to listen config changes on runtime, and it's also just a limit.

I'm wondering if you can expose that option so I don't have to fork the library only for changing a number 😆. I didn't found any other library that met my requirements as this one does.

Thank you!

Documentation error

The main documentation page (http://lorenwest.github.io/node-config/latest/) says:

hostname is the $HOST environment variable if set, otherwise the hostname found from require('os').hostname()

It should say something like:

hostname is the $HOST environment variable if set, otherwise the $HOSTNAME environment variable 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

starting without file watch

as of today, it looks like you can't start without file watch already activated (watchForConfigFileChanges is called at startup without a parameter, which causes it to start with the default value).

i know i can watchForConfigFileChanges later with 0, but it's too late for me as the node already fails because there are too many file descriptors open.

can you release an option (environment variable, creation parameter) that will enable me to start running without file watch being activated?

Thanks.

Json code update at runtime

I am trying to update config from a json (not editing the json file).
Can be done,or I am missing something?

something like this:

config = require('config');
config = { "Customer": {
      "dbName": "customers",
      "dbHost": "localhost",
      "dbPort": 5984,
      // Database synchronization frequency
      "syncFrequency": 60
    }
  };

Using environment variables to override config element name with more than one underscore fails

Problem on environment variable parsing

Consider following json configuration file:

{
    "my_app": {
        "db_user_name": "test"
    }
}

Now trying to override the "db_user_name" by using environment variables with the following syntax will fail:

export CONFIG_my__app_db__user__name="overridenUser"

When parsing environment variables the node-config first takes the "CONFIG" part away then replaces all double underscores with "`" and splits the string based on single underscores. When trying to convert back the temporary character to single underscore only the first occurrence is replaced and rest are left untouched. This causes the name not to match and attribute is not overridden.

Following code is trying to change the temporary '`' characters back to underscore but does so only for the first found character in the string:

var partName = parts[i].replace('`','_');

This can be fixed by replacing above with the following code:

var partName = parts[i].replace(/`/g, '_');

Should we use the global NODE_CONFIG variable ?

Greetings,

I noticed a declaration of the global variable NODE_CONFIG to run your module as a singleton. I wondering if it's better to use it directly or to declare a new var config = require("config") within every sub-modules ?

Cheers !

YAML files don't work anymore

I just upgraded to 0.4.14 from 0.4.11. Broke my app with the message:

/path/to/node_modules/config/lib/config.js:728
    throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3)
          ^
Error: Cannot parse config file: '/path/to/config/default.yaml': Error: Cannot find module 'yaml'
    at [object Object]._parseFile (/path/to/node_modules/config/lib/config.js:728:11)
    at /path/to/node_modules/config/lib/config.js:597:25
    at Array.forEach (native)
    at /path/to/node_modules/config/lib/config.js:594:14
    at Array.forEach (native)
    at [object Object]._loadFileConfigs (/path/to/node_modules/config/lib/config.js:593:13)
    at new <anonymous> (/path/to/node_modules/config/lib/config.js:99:5)
    at Object.<anonymous> (/path/to/node_modules/config/lib/config.js:1081:64)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)

I notice you removed the YAML parser from the production dependencies and I don't understand why. Also, the files committed to the node-modules directory don't appear in my installation (via npm).

null values

Since node-config always returns an object (with the config prototype attached) null values are returned as empty objects.

This was somewhat confusing to me the first time. Is there a way to test if a value is null? Shouldn't null values simply be returned as null, or would that break the concept?

Expose node-configs perceived environment

I think node-config should expose it's perceived environment in some way. I'm writing a server software that needs a config set but i don't want to set a default for it (it's a config similar to the rails secret token). So i check if it's undefined and i want to print something helpful (like add this to one of these files).

Currently i resort to just reimplementing what you're already doing in node-config to map up which files it checks.

I think there should be methods/fields to get the deployment, and a list of config files that node-config will check for the current deployment.

Great module, thanks for all the work :)

Environment Variables in Config

Is there any way that I can use environmental variables in a configuration file? If not can you add that as a feature?

Use Case: Platform as a Service (like Nodejitsu) you upload your code and services like mongodb is provided via environmental variables to include authentication.

Nested setModuleDefaults overwrites original config values

With the following default.yaml:

modules:
  login:
    users:
      tom: somePass
      bob: somePass

Running this script:

var CONFIG = require('config');
var mods = CONFIG.setModuleDefaults('modules', {}),
    login = mods.setModuleDefaults('login', {});
console.log(login.users);

sets the 'login' submodule to {} instead of retaining the values defined there. That last line produces undefined.

Change path and Files names

I need to change the path and filename, so you can tell what file and path to use.

Changing

CONFIG_DIR = process.env['NODE_CONFIG_DIR'] || process.cwd() + '/config',
runtimeJsonFilename = process.env['NODE_CONFIG_RUNTIME_JSON'] || CONFIG_DIR + '/runtime.json'

Which is the best way to do it?

npm install warning

Writing package.json like this.

, "dependencies": {
"express": "2.4.6"
, "connect": "1.6.4"
, "ejs": ">= 0.0.1"
, "nko": ""
, "socket.io": "0.7.9"
, "connect-auth": "0.4.0"
, "connect-redis": "1.0.7"
, "request": "
"
, "config": "*"
}

and then

$ npm install
npm WARN [email protected] package.json: 'modules' object is deprecated
[email protected] ./node_modules/config
├── [email protected]
└── [email protected]

I have no idea of this worning..

hostName not setting as documented

Currently, $HOST and/or $HOSTNAME variables are completely ignored, unless OS.hostname() throws an error.

I've got dozens of different environments/servers and some of them are actually VMs where OS.hostname() is possibly unpredictable as they are spun up and down, and even if it is predictable, it is not always easily discoverable (by me, because I am not the admin and don't even always know who is).

I either need $HOST or $HOSTNAME to override OS.hostname() or I need a third config variable called $HOSTTYPE or something. I understand that making HOST override OS.hostname() could theoretically break peoples configurations (although it is what the documentation currently incorrectly indicates will happen)...

I really don't care which way we go, and, am ready to issue a pull request with either change implemented. I'll paste the code for both changes below; just let me know if you would like a pull request for either one:

Option 1 (possibly breaking change): Making HOST or HOSTNAME override the OS.hostname() setting (so that it matches the documentation, as documented on line 550 of config.js):

  // Determine the host name. The variable is set from the FIRST of
  // of the following to have a non-falsey value: $HOST, $HOSTNAME, or OS module
  try {
    var OS = require('os');
    var hostName = OS.hostname();
  } catch (e) {}
  hostName = process.env.HOST || process.env.HOSTNAME || hostname;
  // Remove any . appendages, and default to null if not set
  hostName = hostName ? hostName.split('.')[0] : null;

Option 2 (non-breaking change with added complexity and flexibility): Adding HOST_TYPE environment variable:

/* <pre>
 *   default.EXT
 *   (hostname).EXT
 *   (hosttype).EXT
 *   (deployment).EXT
 *   (hostname)-(hosttype).EXT
 *   (hostname)-(deployment).EXT
 *   (hosttype)-(deployment).EXT
 *   (hostname)-(hosttype)-(deployment).EXT
 *   local.EXT
 *   local-(hosttype).EXT
 *   local-(deployment).EXT
 *   local-(hosttype)-(deployment).EXT
 *   runtime.json
 * </pre>
 *
 * <p>
 * EXT can be yaml, coffee, json, or js signifying the file type.
 * yaml is in YAML format, coffee is a coffee-script,
 * json is in strict JSON format, and js is a javascript executable file that is
 * require()'d with module.exports being the config object.
 * </p>
 *
 * <p>
 * (hostname) found from require('os').hostname(), unless this function throws an error, in which
 * case it falls back on the $HOST or $HOSTNAME environment variable if set. You can not overwrite
 * this variable through settings, but, rather you have to overwrite it on a machine
 * wide environment variable from outside of node.
 * </p>
 *
 * <p>
 * (hosttype) is the type of host, found in the $HOST_TYPE environment variable.
 * Defaults to 'development'.
 * </p>
 *
 * <p>
 * (deployment) is the deployment type, found in the $NODE_ENV environment
 * variable.  Defaults to 'development'.
 * </p>
 *
 * <p>
 * This becomes extremely useful if you have multiple types of hosts, such as
 * 'DEV', 'QA', 'STAGE' and 'PROD' where you are doing test deployments that require
 * different third party integration settings based on host type and deployment.
 * For instance, if you have different REST or SOAP routes that your app hits based
 * on whether it is in a PROD-like environment vs a QA-like env.
 * </p>
 *
 * <p>
 * You can get extremely fine-grained with this, which can be necessary if you are
 * at a large corporation with dozens of different environments and servers. Just
 * think of hostname as being the specific server or VM the code is going to run from
 * (which will probably be much more granular than you will typically need, and also, this
 * can easily change if you are not in control of the environment you are deploying to), hosttype
 * as being the type of environment you are running out of (dev, qa, stage, prod, etc),
 * and deployment as being a release target, or cluster perhaps (qa2s1, 13-03-15-release, etc)
 * </p>
 *
 * <p>
 * The runtime.json file contains configuration changes made at runtime either
 * manually, or by the application setting a configuration value.
 * </p>
 *
 * @protected
 * @method _loadFileConfigs
 * @return {this} The configuration object
 */
Config.prototype._loadFileConfigs = function() {

  // Initialize
  var t = this;

  // Singleton
  if (originalConfig)
    return t;

  // Determine the host name from the OS module, $HOST, or $HOSTNAME
  // Remove any . appendages, and default to null if not set
  try {
    var OS = require('os');
    var hostName = OS.hostname();
  } catch (e) {
    hostName = process.env.HOST || process.env.HOSTNAME;
  }
  hostName = hostName ? hostName.split('.')[0] : null;

  // Get the deployment type from NODE_ENV
  var deployment = process.env.NODE_ENV || 'development';
  var hostType = process.env.HOST_TYPE || 'development';

  // Read each file in turn
  var baseNames = ['default', hostName, hostType, deployment, hostName + '-' + hostType, hostName + '-' + deployment, hostType + '-' + deployment, hostName + '-' + hostType + '-' + deployment, 'local', 'local-' + hostType, 'local-' + deployment, 'local-' + hostType + '-' + deployment];

Thanks!

runtime.json file error

When I don't run server start script from it's directory, I get this exception:

Cannot write runtime.json file Error: ENOENT, no such file or directory '//config/runtime.json'
fs.js:837
    throw errnoException(errno, 'watch');
          ^
Error: watch ENOENT
    at errnoException (fs.js:806:11)
    at FSWatcher.start (fs.js:837:11)
    at Object.fs.watch (fs.js:861:11)
    at Config.watchForConfigFileChanges (/home/ubuntu/www/sandbox.acaline-server-node/node_modules/config/lib/config.js:469:37)
    at Object.<anonymous> (/home/ubuntu/www/sandbox.acaline-server-node/node_modules/config/lib/config.js:1090:20)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)

Make file watching compatible across node versions and OS platforms

File watching changed between production Node.js versions 0.4.x and 0.6.x. The 0.4.x style is supported in 0.6.x, but only for non-windows machines.

Unfortunately for a package like node-config that has to work between node.js versions as well as across OS platforms, this means poking around to see what file watching paradigm is available on the system in use.

The old-style version is available on windows 0.6.x, but it throws an exception if you try to use it. This probably means looking at version numbers and O/S types vs. function discovery.

At any rate, the issue is to make it work on all versions and all OS platforms.

runtime json file modification ( User updating manually through txt editor ) is not gitting notified on the running node application

Hi,
I was looking for a mode module to maintain the config files for our node application, where i got your node-config module. one of the nice feature which i was looking is run time update. but when i tried as mentioned in your documentation, the manual change is not getting notified, i mean the call back method is not getting called.

snippet of my code:

// Watch for any changes to the customer configuration
21 conf.CONFIG.watch(conf.CONFIG, conf.CONFIG.Emptybody_Ecode, function(object, propertyName, priorValue, newValue) {
22 console.log("Configuration " + propertyName + " changed from " + priorValue + " to " + newValue);
23 console.log(conf.CONFIG.Emptybody_Ecode, conf.CONFIG.Emptybody_message)
24 console.log(conf.CONFIG.Emptybody_Ecode, conf.CONFIG.Emptybody_message)
25 });

Emptybody_Ecode - is a parameter in runtime.json file in default config folder.
CONFIG - is the object returned by the node-config module.
when i modify the Emptybody_Ecode in runtime.json file, the call back is not getting called.
hope this helps to understand my issue. if not please let me know you questions.

please let me know what is wrong in the use-age.

v0.4.12 doesn't run when runtime config file isn't present

If you remove (or in my case, never had) the runtime config fille, fs.watch throws the following error:

Jons-MacBook-Pro:node-config jon$ npm test

> [email protected] test /Users/jon/Sites/node-config
> ./node_modules/vows/bin/vows test/*.js --spec


node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: watch ENOENT
    at errnoException (fs.js:644:11)
    at FSWatcher.start (fs.js:671:11)
    at Object.watch (fs.js:699:11)
    at [object Object].watchForConfigFileChanges (/Users/jon/Sites/node-config/lib/config.js:461:37)
    at Object.<anonymous> (/Users/jon/Sites/node-config/lib/config.js:1047:20)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)

Can't get the file loading to work

It seems to only load my defaults file. I've tried different production settings and files but nothing seems to be overwriting the default. When removing the defaults file no configuration properties were available at all.

For example I create a file development.yaml in myapp/config

then I do
$ export NODE_ENV=development
$ node app.js

This doesn't make it load the config/development.yaml

I've tried running the tests but I get this error:

$ npm test config
npm WARN package.json [email protected] No repository field.

[email protected] test me/node_modules/config
./node_modules/vows/bin/vows test/*.js --spec

sh: ./node_modules/vows/bin/vows: No such file or directory
npm ERR! weird error 127
npm ERR! not ok code 0

I have tried to install vows, also with -g, but the same errors occurs. Anything I can do to debug?

More flexible configs proposal

Currently I see that there are the following configs are tried to load (https://github.com/lorenwest/node-config/blob/35a2be05c483bd82e9374ad4d5dae2ed61266d7b/lib/config.js#L600):

['default',
 hostName,
 deployment,
 hostName + '-' + deployment,
 'local',
 'local-' + deployment];

And this is not flexible enough for my case:

  1. I have a game that runs 10-process production cluster + 2-process staging cluster on a single server. Each is run with it's own deployment:
  • NODE_ENV="ha-prod-w1"
  • ...
  • NODE_ENV="ha-prod-w10"
  • NODE_ENV="ha-stage-w1"
  • NODE_ENV="ha-stage-w2"
  1. I use hostName + '-' + deployment config naming and each of the processes loads it's own file ('w176' is a hostname, 'ha-prod' and 'ha-stage'):
  • w176-ha-prod-w1.yaml
  • ...
  • w176-ha-prod-w10.yaml
  • w176-ha-stage-w1.yaml
  • w176-ha-stage-w2.yaml
  1. And there are some configs that I would share between all of the prod processes, and separately between all of the stage processes.

I could have added local.yml into corresponding dirs but it would like to use an SCV for configs too and this would lead to a conflict.

I could also fake env.HOST = 'w176-ha-prod' and env.HOST = w176-ha-prod along with using env.NODE_ENV = 'w1' .. 'w10' and this is what I'm likely going to do to solve my issue.

But what I would really like is to be able to somehow add one more level (or just more levels) between hostname and deployment (NODE_ENV) in the hierarchy. Suppose a following case: we use NODE_ENV = 'ha-prod.w1' and this would make node-config to split the name and try different names incrementally:

  • ha-prod.ext
  • ha-prod.w1.ext
    I would create ha-prod.yaml and ha-stage.yaml with corresponding common info.

(JSON) When config files are reloaded, arrays are converted to arguments-like objects and some values are removed

Hey,

I'm using config to load in a JSON object that looks something like this:

    {
        "array" : [
            {
                "integerKey" : 80,
                "subObject" : {
                    "boolean" : true,
                    "deepObject" : {
                        "someString" : "somevalue"
                    }
                }
            }
        ],
        "string" : "foo"
    }

This works fine, and I can edit this file as long as the process using it is not running.

However, if I edit the file while the process is running, it updates the json file to this:

    {
        "array" : {
            "0" : {
                "subObject" : {
                    "boolean" : true,
                    "deepObject" : {
                        "someString" : "somevalue"
                    }
                }
            }
        },
        "string" : "foo"
    }

You'll notice that the first key (with an integer value) of the first object in the array is completely missing, and the array is turned into an object.

Then, when trying to restart the process (in this case it's a proxy, so this is especially cumbersome because I don't want my process to be stopped for long), the array won't parse as such, the integer key is missing, and the app blows up.

In an attempt to circumvent this, I made a quick and dirty recursive clone to feed the config through, assuming that the issue was that I was changing the object after loading it in:

    // deep clone a config file
    var cloneConfig = function(o){
        var r = {},
                getValue = function(v){
                    var t = typeof v;
                    if(t === 'object' && !Array.isArray(v)){
                        return cloneConfig(v);
                    } else if(Array.isArray(v)){
                        var a=[];
                        for(var n=0,l=v.length;n<l;n++){
                            a.push(getValue(v[n]))
                        }
                        return a
                    } else if(t !== 'function'){
                        return v
                    }
                }
        for(var k in o){
            if(!o.hasOwnProperty(k)) continue;
            r[k] = getValue(o[k]);
        }
        return r;
    }

I checked the docs, and they don't seem to mention an ability to turn off automatic loading of files. In addition, replacing arrays with objects seems like a bug.

What am I doing wrong?

Removing "Writing runtime json file" console output

Hi there!

First of all, great lib :D it's super handy :D.

Very small request, could it be possible to remove the console.log output on line 644?

It's nothing really big and probably more of a personal opinion but I think that third party modules should have configurable/controllable outputs or no output at all to keep the console clean. What do you think?

Thanks!

config does not work with mounted apps

Suppose I have an Express app that is providing api endpoints. This API app will work fine if I run it standalone.

//Api App

var express = require('express'),
    app = express(),
    config = require('config');

//add some init bits here that use  config

But if I want to mount it in another Express app (in a separate directory), roughly like so...

//Main App

var express = require('express'),
    app = express(),
    config = require('config'),
    apiServer = require(PATH_TO_API_APP);

//add some init bits here that INCLUDING 
app.use('/api', apiServer);

Any code that uses config in the API app, bombs as it looks at the Parent App's config instance

This appears to be a two-part issue.

  1. Creating a global 'singleton'

    global.NODE_CONFIG = global.NODE_CONFIG ? global.NODE_CONFIG : new Config();
    

    ...Makes sense from a performance perspective, but this may assume too much. The assumption that we have a single app, with a single config is not always correct.

  2. The following line

    CONFIG_DIR = process.env['NODE_CONFIG_DIR'] || process.cwd() + '/config'
    

    process.cwd() will return the path to the PARENT app, not the child when it is mounted as described above.

Any thoughts on this? I'm working up a fix for this in my branch, but I'd like feedback from the current creator/maintainers on this.

More info: T.J. is demonstrating/proposing this pattern (akin to engines, in Rails) here http://vimeo.com/56166857, so I suspect this issue will come up again in the future.

Realtime how to resolve and overwrite

Not sure if this is an issue or me misunderstanding the use of realtime changes to configuration properties.

In my defaults I have a setting called tmpfileLocation. This is a relative path like "../tmp". When I start my application I would like to resolve it to an absolute path and overwrite the exiting one. This is what I tried:

config.tmpfileLocation = path.join(__dirname, config.tmpfileLocation);

The tmpfileLocation will show up in realtime.json. The problem is that on every restart of my application the __dirname gets prepended to the already resolved path. Is there a way to clear tmpfileLocation from the realtime properties when I restart my app?

Or am I just going about this the wrong way...?

prefix for hostname

It would be nice if the 'hostname' based configs had a prefix or suffix, such as hostname-somehost.yaml - that way I could git ignore config/hostname-* in my source repository.

I guess I could use an environment and ignore *production for example, so that could be a workaround. Just a suggestion.

Turning off runtime.json

Perhaps this exists, but I can't seem to track it down. I'd like to clean up the runtime.json file when node exits so that it doesn't get persisted between sessions. Is there a way to do this within node-config?

file watcher prevents process auto exit

is there a way to disable the file watcher via config? a very simple:

> var config = require('config');
> <EOF> 

should quit the process, but doesn't. commenting out the file watcher in the Config() init fixes this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.