• This repository has been archived on 15/Feb/2021
  • Stars
    star
    102
  • Rank 335,584 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 13 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

Handle configuration once and for all

config-chain

A module for loading custom configurations

NOTE: Feature Freeze

locked

This module is frozen.

In general, we recommend using rc instead, but as npm depends on this, it cannot be changed.

Install

yarn add config-chain

# npm users
npm install --save config-chain

Usage

const cc = require('config-chain');

console.log(cc.env('TERM_', process.env));
/*
{ SESSION_ID: 'w1:5F38',
  PROGRAM_VERSION: '3.1.2',
  PROGRAM: 'iTerm.app' }
*/

The .env function gets all the keys on the provided object which are prefixed by the specified prefix, removes the prefix, and puts the values on a new object.


Full Usage

  // npm install config-chain

  var cc = require('config-chain')
    , opts = require('optimist').argv //ALWAYS USE OPTIMIST FOR COMMAND LINE OPTIONS.
    , env = opts.env || process.env.YOUR_APP_ENV || 'dev' //SET YOUR ENV LIKE THIS.

  // EACH ARG TO CONFIGURATOR IS LOADED INTO CONFIGURATION CHAIN
  // EARLIER ITEMS OVERIDE LATER ITEMS
  // PUTS COMMAND LINE OPTS FIRST, AND DEFAULTS LAST!

  //strings are interpereted as filenames.
  //will be loaded synchronously

  var conf =
  cc(
    //OVERRIDE SETTINGS WITH COMMAND LINE OPTS
    opts,

    //ENV VARS IF PREFIXED WITH 'myApp_'

    cc.env('myApp_'), //myApp_foo = 'like this'

    //FILE NAMED BY ENV
    path.join(__dirname,  'config.' + env + '.json'),

    //IF `env` is PRODUCTION
    env === 'prod'
      ? path.join(__dirname, 'special.json') //load a special file
      : null //NULL IS IGNORED!

    //SUBDIR FOR ENV CONFIG
    path.join(__dirname,  'config', env, 'config.json'),

    //SEARCH PARENT DIRECTORIES FROM CURRENT DIR FOR FILE
    cc.find('config.json'),

    //PUT DEFAULTS LAST
    {
      host: 'localhost'
      port: 8000
    })

  var host = conf.get('host')

  // or

  var host = conf.store.host

Finally, flexible configurations! πŸ‘Œ

Custom Configuations

var cc = require('config-chain')

// all the stuff you did before
var config = cc({
      some: 'object'
    },
    cc.find('config.json'),
    cc.env('myApp_')
  )
  // CONFIGS AS A SERVICE, aka "CaaS", aka EVERY DEVOPS DREAM OMG!
  .addUrl('http://configurator:1234/my-configs')
  // ASYNC FTW!
  .addFile('/path/to/file.json')

  // OBJECTS ARE OK TOO, they're SYNC but they still ORDER RIGHT
  // BECAUSE PROMISES ARE USED BUT NO, NOT *THOSE* PROMISES, JUST
  // ACTUAL PROMISES LIKE YOU MAKE TO YOUR MOM, KEPT OUT OF LOVE
  .add({ another: 'object' })

  // DIE A THOUSAND DEATHS IF THIS EVER HAPPENS!!
  .on('error', function (er) {
    // IF ONLY THERE WAS SOMETHIGN HARDER THAN THROW
    // MY SORROW COULD BE ADEQUATELY EXPRESSED.  /o\
    throw er
  })

  // THROW A PARTY IN YOUR FACE WHEN ITS ALL LOADED!!
  .on('load', function (config) {
    console.awesome('HOLY SHIT!')
  })

API Docs

cc(...args)

MAKE A CHAIN AND ADD ALL THE ARGS.

If the arg is a STRING, then it shall be a JSON FILENAME.

RETURN THE CHAIN!

cc.json(...args)

Join the args into a JSON filename!

SYNC I/O!

cc.find(relativePath)

SEEK the RELATIVE PATH by climbing the TREE OF DIRECTORIES.

RETURN THE FOUND PATH!

SYNC I/O!

cc.parse(content, file, type)

Parse the content string, and guess the type from either the specified type or the filename.

RETURN THE RESULTING OBJECT!

NO I/O!

cc.env(prefix, env=process.env)

Get all the keys on the provided object which are prefixed by the specified prefix, removes the prefix, and puts the values on a new object.

RETURN THE RESULTING OBJECT!

NO I/O!

cc.ConfigChain()

The ConfigChain class for CRAY CRAY JQUERY STYLE METHOD CHAINING!

One of these is returned by the main exported function, as well.

It inherits (prototypically) from ProtoList, and also inherits (parasitically) from EventEmitter

It has all the methods from both, and except where noted, they are unchanged.

LET IT BE KNOWN THAT chain IS AN INSTANCE OF ConfigChain.

chain.sources

A list of all the places where it got stuff. The keys are the names passed to addFile or addUrl etc, and the value is an object with some info about the data source.

chain.addFile(filename, type, [name=filename])

Filename is the name of the file. Name is an arbitrary string to be used later if you desire. Type is either 'ini' or 'json', and will try to guess intelligently if omitted.

Loaded files can be saved later.

chain.addUrl(url, type, [name=url])

Same as the filename thing, but with a url.

Can't be saved later.

chain.addEnv(prefix, env, [name='env'])

Add all the keys from the env object that start with the prefix.

chain.addString(data, file, type, [name])

Parse the string and add it to the set. (Mainly used internally.)

chain.add(object, [name])

Add the object to the set.

chain.root {Object}

The root from which all the other config objects in the set descend prototypically.

Put your defaults here.

chain.set(key, value, name)

Set the key to the value on the named config object. If name is unset, then set it on the first config object in the set. (That is, the one with the highest priority, which was added first.)

chain.get(key, [name])

Get the key from the named config object explicitly, or from the resolved configs if not specified.

chain.save(name, type)

Write the named config object back to its origin.

Currently only supported for env and file config types.

For files, encode the data according to the type.

chain.on('save', function () {})

When one or more files are saved, emits save event when they're all saved.

chain.on('load', function (chain) {})

When the config chain has loaded all the specified files and urls and such, the 'load' event fires.

More Repositories

1

essential-eth

πŸͺΆ An alternative to ethers & web3 that's 10x smaller
TypeScript
303
star
2

mailto

πŸ’Œ ⚑️ The mailto encoder
JavaScript
199
star
3

eth-labels

πŸ“ƒ A public dataset of crypto addresses labeled
HTML
185
star
4

drain

πŸ«— Drain a wallet of tokens FAST
TypeScript
126
star
5

claimable

🚁 Aggregates all known Ethereum airdrops and POAPs on one page
TypeScript
110
star
6

bitfinex

Bitcoin trading scripts written in Python
Python
104
star
7

swim

πŸŠβ€β™€οΈ Switch between multiple vimrc files
Shell
84
star
8

RelativePath

VSCode Relative path plugin
TypeScript
69
star
9

txn.xyz

🧨 Connect any wallet to web3 instantly
TypeScript
57
star
10

vimrc-builder

β“₯ vimrc file builder
JavaScript
54
star
11

skrub

Irreversible file deletion on every OS
JavaScript
50
star
12

satoshi-bitcoin

Convert precisely between Satoshi and Bitcoin
JavaScript
42
star
13

o-o

πŸ‘“ Bookmarks but for the terminal
JavaScript
31
star
14

spellingBee

🐝 βž• :octocat: Correct spelling of README's.
Python
29
star
15

pluc

πŸ‘Œ Instant terminal aliases
JavaScript
27
star
16

free-eth-node

πŸ”₯β›“ Connect to any EVM chain instantly
TypeScript
25
star
17

lat-lng

πŸ“πŸŒŽ ⚠️Currently offline ⚠️A micro-service for physical address -> lat-lng
JavaScript
24
star
18

cryptoVal

SMS based cryptocurrency client (Bitcoin, LiteCoin, etc.)
JavaScript
20
star
19

rusty-days

πŸŽ“ My journey from JavaScript to Rust
Brainfuck
17
star
20

to-type

The way typeof should be
JavaScript
16
star
21

arrford

Array to human readable list converter
JavaScript
14
star
22

openg

Open Github pages for npm modules in-browser
JavaScript
14
star
23

opencast

APIs for Farcaster data fast locally
TypeScript
13
star
24

rainge

Make copyright's great again
JavaScript
12
star
25

woman

man pages that make you say "woah"
JavaScript
11
star
26

puffer-fish

A cli for puffing your repo with a fake language. Hit GitHub trending in a less popular language.
Bro
10
star
27

hyperterm-bold-tab

Bold your active tab in hyperterm
JavaScript
10
star
28

fuhk

πŸ–• Get all "bad words" in a string
JavaScript
10
star
29

react-pro-tips

πŸ™Œ Take your React skills beyond average
10
star
30

object-types

Get JavaScript object types
JavaScript
9
star
31

skrub-cli

Irreversible file deletion on every operating system
JavaScript
9
star
32

accepteth

πŸ’Έ Accept crypto payments in 60 seconds
TypeScript
9
star
33

meread

πŸ™ŒπŸ€–πŸ™Œ Automating a beautiful readme
JavaScript
8
star
34

gmap

Google Maps' Unofficial Url Wrapper
JavaScript
7
star
35

uplift

πŸ™Œ A website for uplifting quotes
JavaScript
7
star
36

sist

Print system information in markdown
JavaScript
6
star
37

catch

An RPC Cache for 10x Faster Ethereum
TypeScript
6
star
38

openm

open npmjs module pages in your browser
JavaScript
5
star
39

intersection

Organize the internet into subject sections like a Newspaper
JavaScript
5
star
40

typewriter

🎹 POC TypeScript -> Flow Converter
JavaScript
5
star
41

dawsbot

Special repo for homepage data
Shell
5
star
42

file-bytes

Get a file's size with Node.js
JavaScript
5
star
43

dotfiles

Mac dotfiles for ⚑️-fast hacking
Shell
5
star
44

www

πŸ‘¨πŸ»β€πŸ”§ My Personal Website - Resume included
JavaScript
5
star
45

btc-price-sms

Get an SMS of the Bitcoin price using Twilio and Coinbase
JavaScript
4
star
46

template

A template directory for testing that will NEVER change.
4
star
47

sf-coffee

An experience journal of San Francisco Coffee shops
HTML
4
star
48

uber-api-example

Uber API Node Trip History Example πŸ•πŸš—
JavaScript
4
star
49

ergodaws

Ergodox key layout
C
3
star
50

script-kitty

url-encoded JavaScript
JavaScript
3
star
51

deep-blue-string

Apply prototype functions to strings deep in data types
JavaScript
3
star
52

duplival

JSON + variables === <3 in only 292 bytes
JavaScript
3
star
53

if-file-read

Read the first valid file in an array
JavaScript
2
star
54

dawsbot.github.io

DEPRECATED. See http://dawsbot.com
HTML
2
star
55

opent

cli to open travis-ci module pages in your browser
JavaScript
2
star
56

soundvisualizer

CU live sound visualization in Atlas Building
Python
2
star
57

cookbook

Your guide for web3 tutorials
Solidity
2
star
58

ClassNotes

Class notes of a computer science major at CU Boulder
2
star
59

degen-tips-readme-action

GH Action to automatically add DEGEN tippers from farcaster to your readme
TypeScript
2
star
60

build-shell-script

Build shell aliases and functions from Node
JavaScript
2
star
61

replace-require-regex

Regex based require/import replacements for strings
JavaScript
2
star
62

syncspin

Democratic Jukebox | HackGT 2014 - DEPRECATED
JavaScript
2
star
63

temp-dir-cp

⚑️ Copy directories to a unique temp location
JavaScript
2
star
64

daily-gwei-frame

Farcaster Frame for Daily Gwei
2
star
65

engines-enforcer

Enforce node engines specified in package.json
JavaScript
2
star
66

regs

Useful regular expressions for JavaScript
JavaScript
1
star
67

.github

1
star
68

candyhack

Python
1
star
69

numberguess

Multiplication fun for kids
HTML
1
star
70

mlh-mapper

⚠️Incomplete ⚠️Graphs the MLH contest locations on a world map
JavaScript
1
star
71

json-fn-file

Apply a function to a json file and save to a file
JavaScript
1
star
72

cuhackwebsite

CUHack website source found here - now https://hackcu.org
HTML
1
star
73

uplift-chrome-ext

πŸ™Œ A minimal AF happy random quote Chrome Extension
1
star
74

get-shell-rc

Get the rc file path for any Linux/Unix Shel
JavaScript
1
star
75

basify

Strip filename extensions
JavaScript
1
star