• Stars
    star
    116
  • Rank 297,839 (Top 6 %)
  • Language
    JavaScript
  • Created almost 12 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Config file reader for node.js projects that detects environment based on NODE_ENV.

getconfig - config fetcher for node.js

Managing configs for different environments is kind of a pain.

In short I wanted it to:

  • Be simple to understand and use
  • Use NODE_ENV environment variable to grab appropriate config
  • Let me just go const config = require('getconfig') from anywhere in the app and have it Just Workโ„ข
  • Allow using different formats (via require hooks)

How to use

  1. npm install getconfig
  2. Create a config/default.json (or config/default.js, anything you can require() will work) file in the same folder as the main entry point (usually project root)
  3. Just require getconfig like so from anywhere in your project:
const Config = require('getconfig');
  1. That's it!

Where to put your config and what to call it

Getconfig looks for a config directory in the same folder as the main entry point of your app. Your configuration files should be contained within that directory.

The configuration files attempted by require, in order, are:

  • config/default
  • config/all
  • config/{{NODE_ENV}}
  • config/local

Note that we don't list extensions, that's because the files are loaded via node's require mechanism, so anything node can require will work.

In the event that NODE_ENV is not set, getconfig will attempt to load dev, devel, develop, and development in its place.

Environment variables

In a lot of situations it's simpler to pass configuration via environment variables, rather than hardcoding it into a config file.

Fortunately, getconfig can fill those in for you. Just set the value of a key to reference the environment variable and it will be expanded inline. For example:

{
    "envVariable": "$ENV_VAR"
}

Note that this will only work for environment variables whose names are within the character set of A-Z, 0-9, and _ (underscore). This is to prevent collisions with things like complex strings that may start with a $.

Environment variables can be made optional by specifying a second $ in the value's name, such as:

{
    "envVariable": "$$ENV_VAR"
}

When an optional environment variable is unspecified, it is removed from that layer of configuration. This allows you to specify a default in config/default and an optional value in config/dev, and if the optional value in config/dev is unset the value from config/default will be used.

Required environment variables may be used in string interpolation like so:

{
    "envVariable": "some ${ENV_VAR}"
}

However when used in interpolation like the above, no type conversions will be applied.

Additionally, since all environment variables are strings, getconfig can also perform type coercion for you by specifying a ::type suffix. The following types are supported out of the box:

{
    "stringArray": "$STRING_ARRAY_VALUE::array",
    "boolean": "$BOOL_VALUE::boolean",
    "booleanArray": "$BOOLEAN_ARRAY_VALUE::array:boolean",
    "date": "$DATE_VALUE::date",
    "dateArray": "$DATE_ARRAY_VALUE::array:date",
    "number": "$NUMBER_VALUE::number",
    "numberArray": "$NUMBER_ARRAY_VALUE::array:number",
    "object": "$OBJECT_VALUE::object",
    "objectArray": "$OBJECT_ARRAY_VALUE::array:object",
    "regex": "$REGEX_VALUE::regex",
    "regexArray": "$REGEX_ARRAY_VALUE::array:regex"
}

The array type is special in that it accepts an optional argument specified by an additional :type suffix, that allows creating an array of a typed value.

In addition to the built in types, it is possible to add your own types like so:

const Errors = require('getconfig/errors');
const Types = require('getconfig/types');

Types.custom = function (val, arg1, arg2) {
    // do some conversion here
    return val;
    // throw new Errors.ConversionError(); // if something failed
};

const Config = require('getconfig');

You can then use ::custom as a suffix in your config and environment variables will be processed through your custom function. If your custom function accepts arguments (in the example above arg1 and arg2) they can be passed like so $$ENV_VAR::custom:arg:arg. Note that every argument will be passed as a string and it is up to your custom function to handle them appropriately.

Self references

Your configuration can also reference variables within itself as part of string interpolation, so a config file like the following is valid:

{
    "port": "$PORT::number",
    "host": "$HOSTNAME",
    "url": "http://${self.host}:${self.port}"
}

This allows you to define a variable once and reuse it in multiple places. This has the same limitations as string interpolation with environment variables however, it will not apply type conversions, and the value referenced must exist. You can refer to deeper keys by using a dot as a path separator like so:

{
    "some": {
        "deep": {
            "value": "here"
        }
    },
    "top": "${self.some.deep.value}"
}

Note that if the contents of a self referencing key is only the reference (i.e. ${self.value} vs http://${self.value}) the reference will be copied not interpolated. This allows you to reference objects in multiple places like so:

{
    "postgres": {
        "user": "pg",
        "database": "test"
    },
    "clientOne": {
        "database": "${self.postgres}"
    },
    "clientTwo": {
        "database": "${self.postgres}"
    }
}

In the above example, the database key under both clientOne and clientTwo will be a reference to the top level postgres object, simplifying configuration reuse.

Explicitly setting the config location

In certain circumstances, when your app isn't run directly (e.g. test runners) getconfig may not be able to lookup your config file properly. In this case, you can set a GETCONFIG_ROOT environment variable to the directory where your config files are located.

.env files

In addition to the above behaviors, getconfig will attempt to load a .env file located in either the config directory or the project root (i.e. one level above the config directory). These .env files are parsed as close to the dotenv package as possible for compatibility's sake.

Cloud Functions

When used in a Google Cloud Function or an AWS Lambda function, getconfig will use the CODE_LOCATION or LAMBDA_TASK_ROOT environment variable, respectively, to automatically locate the appropriate root. This means that you can include your config directory in your function deployment and things should work as you would expect them to.

Note: Google Cloud Functions automatically set NODE_ENV to "production" when deployed, however Lambda leaves NODE_ENV unset by default.

Environment

getconfig will always fill in the getconfig.env value in your resulting config object with the current environment name so you can programatically determine the environment if you'd like. If no NODE_ENV is set it will also set getconfig.isDev to true.

CLI

getconfig also includes a small helper tool for debugging and inserting values from your config into shell scripts and the like, it can be used like:

getconfig [path] config.value

The path parameter is optional and allows you to define the root of your project, the default is the current working directory. The second parameter is the path within the config to print.

Changelog

  • 4.5.0
    • Add support for .env files.
    • Fix bug with multiple variables in interpolation.
  • 4.4.0
    • Add the all layer, which loads before the NODE_ENV layer but after default and can help eliminate the need for multiple files with the same contents.
  • 4.3.0
    • Include a CLI tool.
  • 4.2.0
    • Allow self references to work correctly outside of string interpolation.
  • 4.1.0
    • Support string interpolation of environment variables and self references.
  • 4.0.0
    • Total rewrite, now supports optional environment variables as well as type coercion and custom type processors.
  • 3.1.0
    • Supports Google Cloud Functions and AWS Lambda functions out of the box.
  • 3.0.0
    • Does not merge arrays from config layers, instead overwrites them entirely with the topmost config's array.
  • 2.0.0
    • Total refactor, now stores config files in a directory and merges them on top of each other for simplicity.
  • 1.0.0
    • Bumping major to get out of 0.x.x range per semver conventions.
    • dev enviroments now look for related config files. So if you've set your $NODE_ENV to development and it will still find a file called dev_config.json.
  • 0.3.0 - Switching from JSON.parse to ALCE to allow single quotes and comments. Better readme.

License

MIT

if you dig it follow @HenrikJoreteg and/or @quitlahok on twitter.

More Repositories

1

hjs-webpack

Helpers/presets for setting up webpack with hotloading react and ES6(2015) using Babel.
JavaScript
1,790
star
2

ICanHaz.js

A clean solution for templating with Mustache.js and jQuery or Zepto
JavaScript
838
star
3

feather-app

as light as a...
JavaScript
718
star
4

create-keyframe-animation

Generate CSS keyframe animations dynamically in the browser with JavaScript.
JavaScript
716
star
5

redux-bundler

Compose a Redux store out of smaller bundles of functionality.
JavaScript
581
star
6

fixpack

A package.json file scrubber for the truly insane.
JavaScript
459
star
7

Capsule

Realtime web app framework for Backbone, socket.io and node.js
JavaScript
415
star
8

Happy.js

$('form').isHappy() โ€“ Lightweight, extensible form validation plugin for jQuery/Zepto.js
JavaScript
412
star
9

html-parse-stringify

Parses well-formed HTML (meaning all tags closed) into an AST and back. quickly.
JavaScript
335
star
10

templatizer

Simple solution for compiling jade templates into vanilla JS functions for blazin' fast client-side use.
JavaScript
303
star
11

money-clip

For managing your client side cache. Tiny wrapper over IndexedDB supporting versioning and max age.
JavaScript
233
star
12

wildemitter

A super lightweight EventEmitter similar to what comes in Node.js, but with a support for wildcard events '*'
JavaScript
213
star
13

emoji-images

replace stuff like โค๏ธ with <img> tags of corresponding images per: http://www.emoji-cheat-sheet.com/
JavaScript
173
star
14

moonboots

A set of conventions and tools for bundle and serving clientside apps with node.js
JavaScript
159
star
15

webrtc.js

WebRTC abstraction for managing it simple to manage multiple peer connections of various types.
JavaScript
157
star
16

hubtags.com

A demo app, built with Ampersand and React as a static Native Web App
JavaScript
137
star
17

andlog

Super-simple, client-side CommonJS logging thingy
JavaScript
97
star
18

github-secret-keeper

Microservice to enable GitHub login for multiple server-less applications.
JavaScript
86
star
19

human-javascript

Book on building sanely architected JS apps
CSS
80
star
20

human-model

Strict models are a drop-in replacement for Backbone models but are far more restrictive and structured.
JavaScript
75
star
21

humanjs-sample-app

Sample app for human javascript book
JavaScript
67
star
22

milliseconds

Insanely lightweight module for converting times to milliseconds.
JavaScript
62
star
23

masters

Repo to follow along with Frontend Masters class
JavaScript
60
star
24

redux-bundler-worker-example

Redux-bundler with store and bundler running inside a worker
JavaScript
58
star
25

clientconfig

Super simple clientmodule for passing config items, such as API connection URLs, debug modes, etc from server to client.
JavaScript
56
star
26

webrtcsupport

Browser module to detect support for WebRTC and extract proper constructors.
JavaScript
55
star
27

internal-nav-helper

Helper function for handling internal navigation in Single Page Apps (SPAs) in ~250 bytes before gzip.
JavaScript
52
star
28

feather-route-matcher

featherweight url to handler matching
JavaScript
42
star
29

redux-bundler-react

Bindings for redux-bundler to React
JavaScript
36
star
30

redux-bundler-example

Example app built with redux-bundler
JavaScript
34
star
31

human-view

A smart base view for Backbone apps, to make it easy to bind collections and properties to the DOM.
JavaScript
33
star
32

humanjs

Application scaffolding and documentation repo for Human JavaScript Apps
JavaScript
32
star
33

ric-shim

requestIdleCallback shim that won't blow up if used in node.js
JavaScript
29
star
34

featherweight

JavaScript
28
star
35

reformer

Self-contained, self-rendering, self-validating forms that can only output valid data.
JavaScript
26
star
36

hapi-dummy-api

Generate dummy APIs for hapi.js, for building clientside apps before the real API is done.
JavaScript
26
star
37

worker-proof

Enables calling out to main thread from a worker to register callbacks, etc.
JavaScript
26
star
38

redux-persist-middleware

Creates Redux middleware that will lazily persist data from certain reducers, when certain actions occur.
JavaScript
26
star
39

react-internal-nav

React component with single 'onInternalNav' callback for handling clicks on <a> local to domain.
25
star
40

babel-plugin-h-children-fix

Allows use of standard babel JSX tools with virtual-dom/h
JavaScript
25
star
41

appcache-serviceworker-generator

Can generate an appcache manifest and ServiceWorker from same abstraction.
JavaScript
24
star
42

image-to-data-uri.js

Clientside module (compatible with clientmodules) that takes an image url, downloads the image and creates a data URI for caching, etc.
JavaScript
23
star
43

tryit

Module to wrap try-catch for better performance and cleaner API.
JavaScript
22
star
44

window-watcher

State object you can listen to for changes to window width.
JavaScript
19
star
45

slugger

Dead simple string slugification (a. la. django) for node and the broswer.
JavaScript
18
star
46

create-selector

Wrapper for reselect to allow deferring creation of selectors.
JavaScript
18
star
47

native-promisify-if-present

Return a promise from a callback-as-last-argument function using native a Promise, but only if native Promises exist.
JavaScript
17
star
48

jquery-sliding-message

Nice way to show messages to users
JavaScript
16
star
49

semi-static

Simple, lazy way to serve a directory of semi-static pages in express.js. Handy for building quick "static" pages inside an otherwise "dynamic" app.
JavaScript
15
star
50

key-tree-store

Simple tool for storing/retrieving objects events based hierarchical key paths.
JavaScript
14
star
51

dot-net-article

13
star
52

loading-stats

Client module for reporting real-world single page application performance back to you in your metrics.
JavaScript
13
star
53

video-recorder

Experimental browser module for recording contents of a `<video>` tag by taking dataURI snapshots of it.
JavaScript
12
star
54

set-query-string

Updates the browser's query string in place, so you can bind it to some dynamic query in your app
JavaScript
11
star
55

fluent-2016

Building a lightweight mobile-web app with React and Redux
JavaScript
11
star
56

time-counter

Dead-simple js module for drawing (or simply measuring) time countdowns or counters in js. Works in node and browser.
JavaScript
11
star
57

timple

Simple templating for service workers using valid javascript files as the template
JavaScript
11
star
58

sinks

Tools for object sync (get it?!), validation, diffing, and immutable deep setting
JavaScript
10
star
59

Yo-Moma

Nerdpoints for the best nerdy yo mama joke. Bonus points for git references.
10
star
60

joreteg.com

My new site
HTML
9
star
61

system-requirements.js

Boxed software has 'em, now the web does too.
JavaScript
9
star
62

jquery.dd

Simple replacement for select boxes that are totally css stylable
JavaScript
9
star
63

favicon-setter

Dead-simple favicon updating from JS. Plays nicely with jQuery and CommonJS but has no dependencies.
JavaScript
9
star
64

redux-bundler-worker

Utilities for running a redux-bundler app inside a worker
JavaScript
9
star
65

clientmodules

A small util for using npm to install clientside packages.
JavaScript
8
star
66

fingertips

Touch event handling for mobile web apps
JavaScript
8
star
67

columnizer

A simple tool for printing text in nice columns in the terminal.
JavaScript
8
star
68

redux-bundler-preact

Preact bindings for redux-bundler
JavaScript
8
star
69

jquery-magic-labels

Grabs content of label tag to display as placeholder inside text inputs
JavaScript
8
star
70

wake-event

Browser module for detecting when your computer wakes up from sleep. Based on Alex MacCaw's clever trick.
JavaScript
7
star
71

preact-nav-helper

Preact component for catching and handling internal links in your application.
JavaScript
7
star
72

mit.joreteg.com

license site I can link to from open source projects
HTML
6
star
73

bind-transforms

Bind models properties to properly prefixed CSS transforms in backbone/humanjs views.
JavaScript
6
star
74

humanjs-resources

Curated collection of simple modules solving specific problems relating to building single page apps.
JavaScript
6
star
75

SoundEffectManager

A simple sound effect manager for playing sounds using the awesome HTML 5 Web Audio API
JavaScript
6
star
76

library-api

Simple, restful, demo JSON API written in Hapi.js
JavaScript
6
star
77

ampersand-local-cache-mixin

Only fetch when your data is old or stale. Easily configurable localStorage cache for ampersand & backbone state objects, models, and collections.
JavaScript
6
star
78

transform-style

Apply transform style property with proper prefix to an element. For use with browserify / CommonJS.
JavaScript
5
star
79

holy-grail-ios-layout

Attempt at holy grail mobile safari layout/behavior.
JavaScript
5
star
80

edui

Codebase for edui workshop
JavaScript
5
star
81

labelr-ampersand

class outline and resources
JavaScript
5
star
82

jsconfbr

Sample code for simple webrtc demo
JavaScript
5
star
83

statey

An observable, extensible state object with derived watchable properties.
JavaScript
5
star
84

extend-object

Underscore's extend method as a standalone Common JS module.
JavaScript
5
star
85

array-next

Advance to the next item in the array looping when hitting the end.
JavaScript
5
star
86

google-cloud-signedurl-test-case

Trying to figure out how to make this work :-/
JavaScript
5
star
87

cookie-getter

Super simple, performant, clientside cookie reader and nothing else. CommonJS and clientmodules compatible.
JavaScript
5
star
88

Half-SASS

A partial SASS implementation written in CF
ColdFusion
4
star
89

add-keyup-events

Emit custom events from an input so you can do stuff like listening for "enter" and "esc" events the same way as you would "keyup".
JavaScript
4
star
90

humanjs-codealong-app

JavaScript
4
star
91

get-css-translated-position

Get position of DOM elements positioned with CSS translate
JavaScript
4
star
92

docs.humanjavascript.com

Docs site for humanjs tools
JavaScript
4
star
93

Strophe.js-Plugins

A collection of strophe plugins that let you work with native JavaScript instead of XML
JavaScript
4
star
94

wakelock-lazy-polyfill

Use nosleep.js as a lazy-loaded polyfill for WakeLock API
JavaScript
4
star
95

rollup-plugin-css

Rollup plugin for aggregating and outputting CSS
JavaScript
4
star
96

labelr

JavaScript
3
star
97

dob-to-age

Determines current age based on a date of birth string YYYY-MM-DD using same weird logic we humans do.
JavaScript
3
star
98

reality

Physics simulation runner for web UIs
JavaScript
3
star
99

dotnet-dashboard.andbang.com

A team dashboard app for And Bang 2.0
JavaScript
3
star
100

parse-dob

Turn a wide range of freeform inputs describing someone's birth date into `YYYY-MM-DD` using locale to get proper day / month order.
JavaScript
3
star