ctrl-env
An alternative way to assert environment variables.
Installation
Yarn is recommended for installation.
$ yarn add ctrl-env
But you can still use npm:
$ npm install --save ctrl-env
Usage
const CtrlEnv = require('ctrl-env')
const ctrlEnv = new CtrlEnv([
['SECRET']
, ['PORT', {required: false}]
], {
prefix: 'TWITTER_FEED'
})
ctrlEnv.assert()
http.on('/feed', (request, response) => {
Twitter.getFeed({
handle: '_experiments'
, secret: ctrlEnv.SECRET
}, (error, feed) => {
if (error) {
throw error
}
response.send(feed)
})
})
http.listen(ctrlEnv.PORT)
$ TWITTER_FEED_SECRET='twitter_secret_key' TWITTER_FEED_PORT=8080 node app.js
$
$ TWITTER_FEED_SECRET='twitter_secret_key' node app.js
Methods v2
constructor(Array environmentVariables, Object options)
The constructor takes an array of environment variables to expect. The variables
themselves can be configured:
const exampleEnvVars = [
['REQUIRED_VARIABLE']
, ['OPTIONAL_VARIABLE', {required: false}]
, ['LIMITED_VARIABLE', {values: ['yes', 'no']}]
, ['TYPED_VARIABLE', {type: 'integer'}]
, ['OPTIONAL_LIMITED_VARIABLE', {required: false, values: ['yes', 'no']}]
, ['NODE_ENV', {prefixed: false}]
]
const ctrlEnv = new CtrlEnv(exampleEnvVars)
The constructor also takes an optional prefix
and separator
. The separator
only determines what seperates the prefix and the variable name:
new CtrlEnv(..., {prefix: 'TEST'})
new CtrlEnv(..., {prefix: 'TEST', separator: '___'})
ctrlEnv.assert()
This method actually reads the environment variables and asserts that they exist
or have the required values. Note: This method is synchronous.
get ctrlEnv.VARIABLE_NAME
To read the environment variable, simply use the variable name without the
prefix as a property of your CtrlEnv
instance. This property is a proper
ES2015 getter that does not have a setter. It cannot be overwritten without
using Object.defineProperty
.
get ctrlEnv.all
This returns an object with all asserted environment variables. This property is
a propert ES2015 getter that does not have a setter. It cannot be overwritten
without Object.defineProperty
.
Note: This deprecates #get() from v1.
License
Copyright (c) 2017 Martin Experiments LLC
MIT (https://www.opensource.org/licenses/MIT)