https://github.com/logdna/env-config-node
Configuration package for reading environment variables
https://github.com/logdna/env-config-node
Last synced: 10 months ago
JSON representation
Configuration package for reading environment variables
- Host: GitHub
- URL: https://github.com/logdna/env-config-node
- Owner: logdna
- License: mit
- Created: 2020-09-28T20:45:10.000Z (almost 6 years ago)
- Default Branch: main
- Last Pushed: 2025-08-21T14:36:24.000Z (11 months ago)
- Last Synced: 2025-09-17T21:49:42.983Z (11 months ago)
- Language: JavaScript
- Size: 63.5 KB
- Stars: 1
- Watchers: 20
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
[](https://coveralls.io/github/logdna/env-config-node?branch=main)
[](#contributors-)
# @logdna/env-config
> Node.js Package to define, document, and assert environment variables
## Install
```
$ npm install --save @logdna/env-config
```
## Test
```
$ npm t
```
## Usage
The recommended way to structure applications with this package is as follows:
```js
// config.js
'use strict'
const Config = require('@logdna/env-config')
const config = new Config([
Config.string('loglevel').default('info')
, Config.number('port').default(3000)
])
module.exports = config
```
```js
// index.js
//
// The following env vars can be set:
//
// LOGLEVEL - defaults to info
// PORT - default to 3000
//
'use strict'
const http = require('http')
const config = require('./config.js')
// This validates that we have the necessary env vars.
config.validateEnvVars()
http.listen(config.get('port'), () => {
log.info('listen', config.get('port'))
})
```
Under the hood, `Config` is a [``][], so use it like one.
This package also provides a way to automatically generate documentation
for the environment variables for a service.
If the `doc` directory does not exist, it can be created using the following:
```
$ mkdir -p doc
```
Then, add a `generate` script to the
service's `package.json` that looks similar to this:
```sh
config-doc config.js > doc/env.md
```
You should also add a link to this document in the `README.md` of the service.
## API
### `new Config(input)`
* `input` [``][] Array of objects that represent a single rule.
Each `input` item should be a `Definition`. See "Static Methods" below.
### Static Methods
---
The following static methods return a `Definition` that can be used.
#### `Config.string(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
This defines a configuration definition for an environment variable that is
a [``][].
Returns: `Definition`
#### `Config.number(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
This defines a configuration defintion for an environment variable that is
a [``][].
Returns: `Definition`
#### `Config.boolean(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
This defines a configuration definition for an environment variable that is
a [``][].
Returns: `Definition`
#### `Config.regex(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
This defines a configuration definition for an environment variable that
matches a [``][].
Returns: `Definition`
#### `Config.enum(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
A single value will be read from the environment variable as described,
but it must exist in the allowed list of [`.values()`](#definitionvaluesarr).
Every `enum` type needs to implement a `.values()` array.
#### `Config.list(name)`
* `name` [``][] Name of the config rule. The environment variable
read for this rule will be `name` uppercased with `-` replaced with `_`.
Much like a CSV - an environment variable will be read and parsed into an array
of a specific type. The type can be of `string`, `boolean`, or `number`.
This is defined by calling [`.type()`](#definitiontypetype).
All empty values generated by trailing characters are removed
### Instance Methods
---
#### `Config#toJSON()`
Returns a JSON representation of the config object.
This will only work for Primitive values, objects, and arrays.
#### `Config#validateEnvVars()`
This should be called to validate that the required environment variables
have been passed and that they satisfy the requirements. If any are not passed,
or do not satisfy the requirements, an error will be thrown.
* Throws: [``][]
| [``][]
| [``](#regexperror)
| [``](#missingenverror)
| [``](#enumerror)
| [``](#requireddefaultmutexerror)
### Definition
This is a private prototype that offers the following methods:
#### `Definition#required()`
Specifies that this env var is required to have a value (env vars are optional by default). This means
that a value must be provided, and it **cannot** be the empty string, `''`.
Returns `this` to allow chaining.
#### `Definition#desc(str)`
* `str` [``][] The description
This sets the description for the env var that will be used for docs.
This is an alias for the `Definition#description(str)` method.
Returns `this` to allow chaining.
#### `Definition#description(str)`
* `str` [``][] The description
This sets the description for the env var that will be used for docs.
Returns `this` to allow chaining.
#### `Definition#default(def)`
* `def` [``][] or [``][] or [``][] The default
This sets the default value of the rule. This does not set the actual env
var, but the value in the config's [``][] will show the default value if the
env var's value is empty.
The default value will be applied for an unset var as well as a value of `''`.
Returns `this` to allow chaining.
#### `Definition#allowEmpty()`
`allowEmpty()` tells the definition to accept an empty value in place of the provided non-empty `.default()`
for cases where an empty value is valid and/or expected. Without this option, the default value will be used when
an empty value is detected for a given type. A common use for this is to allow `''` as a value for a
`.string()` definition. In other words, `allowEmpty()` is a no-op without a `default()`.
The empty values for the config types supported by this package are as follows:
| Type | Final Value |
| --- | --- |
| string | `''` |
| number | `0` |
| boolean | `false` |
| list | `[]` |
#### `Definition#toJSON()`
Returns a JSON representation of the configuration `Definition`.
#### `Definition#match(re)`
* `re` [``][] or [``][] The matching regular expression
This method can only be used with `Config.regex()`. Otherwise, an error will
be thrown.
Returns `this` to allow chaining.
#### `Definition#min(n)`
* `n` [``][] The minimum value for the rule
This method can only be used with `Config.number()`. Otherwise, an error will
be thrown.
Returns `this` to allow chaining.
#### `Definition#max(n)`
* `n` [``][] The maximum value for the rule
This method can only be used with `Config.number()`. Otherwise, an error will
be thrown.
Returns `this` to allow chaining.
#### `Definition#values(arr)`
* `arr` [``][] An array of acceptable values for an `enum` type.
This method can only be used with [`Config.enum()`](#configenumname).
The final value must exist in the values `arr`, or an error is thrown.
#### `Definition#type(type)`
* `type` [``][] The type of value expected within a `list`
can be one of:
* `number`
* `boolean`
* `string`
#### `Definition#separator(value)`
* `value` [``][]|[``][] The value used to split a single value into an array
**default**: `/\s+|,/`
## Custom Errors
### `'MissingEnvError'`
* [``][]
* `name` [``][] Static value of `MissingEnvError`
* `type` [``][] Describes the definition: `string`, `number`,
`boolean`, `regex`, or `enum`
This error is thrown if [`Definition#required`](#definitionrequired) was used,
but no such environment variable or value was discovered.
### `'RequiredDefaultMutexError'`
* [``][]
* `name` [``][] Static value of `RequiredDefaultMutexError`
* `type` [``][] Describes the definition: `string`, `number`,
`boolean`, `regex`, or `enum`
This error is thrown if [`Definition#required`](#definitionrequired) **and**
[`Definition#default`](#definitiondefault) are used together in a definition. A non-empty value must
be provided for `required` variables, thus setting a default value for those
is a dead code path. These two options are mutually exclusive.
### `'RegExpError'`
* [``][]
* `name` [``][] Static value of `RegExpError`
* `expected` [``][] The regular expression that is expected to
match the discovered value
* `actual` *(Any)* The value that was discovered in the environment
* `env` [``][] The name of the evironment variable that is supposed
to hold the value (upper cased with underscores, e.g. `MY_VARIABLE`)
This error is thrown if [`Config.regex()`](#configregexname) was used,
but the discovered value in the environment did not match the pattern.
### `'EnumError'`
* [``][]
* `name` [``][] Static value of `EnumError`
* `expected` [``][] The list of acceptable values for the definition
* `actual` *(Any)* The value that was discovered in the environment
* `env` [``][] The name of the evironment variable that is supposed
to hold the value (upper cased with underscores, e.g. `MY_VARIABLE`)
This error is thrown if [`Config.regex()`](#configregexname) was used,
but the discovered value in the environment did not match the pattern.
### `'ListError'`
* [``][]
* `name` [``][] Static value of `EnumError`
* `expected` [``][] The list of acceptable values for the definition
* `actual` *(Any)* An invalid value that found withing the list
* `input` [``][] The the value of the environment variable after it was parsed and sanitized
* `original` [``][] The original value from the environment variable
* `type` [``][] The defined value type of the list property
* `env` [``][] The name of the evironment variable that is supposed
to hold the value (upper cased with underscores, e.g. `MY_VARIABLE`)
This error is thrown if [`Config.list()`](#configlistname) was used,
but the discovered value in the environment contained an invalid value
[``]: https://mdn.io/array
[``]: https://mdn.io/boolean
[``]: https://mdn.io/map
[``]: https://mdn.io/number
[``]: https://mdn.io/object
[``]: https://mdn.io/Primitive
[``]: https://mdn.io/RegExp
[``]: https://mdn.io/string
[``]: https://mdn.io/TypeError
[``]: https://mdn.io/RangeError
[``]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

Evan Lucas
💻 📖

Darin Spivey
💻 📖

Jacob Hull
🚧

Eric Satterwhite
💻
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!