env
Simple, predictable, 0-dependency environment variable management tool for NodeJS, written in Typescript and compiled to es3 for high compatibility.
The env
npm package has fallen into disrepair and destitution, and unfortunately the creator appears unresponsive to pull requests that would address the open issues. This is my solution.
Installation
$ npm i @camsmith145/env
or
$ yarn add @camsmith145/env
Usage
Import environment variables from a json file or an exported js object. The package exports a function which accepts the path to a file.
const {env} = require( '@camsmith145/env' )
env() /* Looks for file named '.env' in process.cwd() */
env('./path/to/file') /* Resolves './path/to/file' in relation to process.cwd() and tries to parse file content */
Parameters
Parameter | Type | Description |
---|---|---|
path |
`string | undefined` |
options |
Object |
A few modifications to the behavior |
Path Resolution
Base of path Parameter Value |
Method of import | Expected File Content |
---|---|---|
undefined |
JSON.parse(/* content of ./.env */) |
Serialized JSON object |
.env |
JSON.parse(/* content of ./.env */) |
Serialized JSON object |
.env.json |
JSON.parse(/* content of ./.env.json */) |
Serialized JSON object |
.env.js |
JSON.parse(/* content of ./.env.js */) |
JS module exports Object
|
Options Object
Property | Type | Default | Description |
---|---|---|---|
ignoreErrors |
`boolean | undefined` | false |
yieldExisting |
`boolean | undefined` | false |
suppressWarnings |
`boolean | undefined` | false |
Value Serialization
Values assigned to properties of process.env
may only be string
s. Therefore, any properties within the env file are serialized using JSON.stringify
prior to property assignment.
Values that are number
, Object
, Array
should be de-serialized upon access using parseInt(n, radix)
, JSON.parse
, etc.
Values that are Date
should be reconstructed using new Date(process.env[key])
.
Example
In ./config/test.env
:
{
"variable_name": {
"key": "value"
}
}
/* index.js */
const {env} = require( '@camsmith145/env' )
env('./config/test.env')
const myObject = JSON.parse(process.env.variable_name)
console.log(myObject.key) // 'value'
MIT Licensed