@camsmith145/env

0-dependency environment variable management in NodeJS

Usage no npm install needed!

<script type="module">
  import camsmith145Env from 'https://cdn.skypack.dev/@camsmith145/env';
</script>

README

env

Simple, predictable, 0-dependency environment variable management tool for NodeJS, written in Typescript and compiled to es3 for high compatibility.

npm: license David: dependencies Travis: build

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 Absolute or relative path to a file. Defaults to ./.env
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 Do not throw an Error if verification of variable assignment to process.env[name] fails.
yieldExisting boolean | undefined false Do not overwrite existing environment variables of the same name. (Sets ignoreErrors to true)
suppressWarnings boolean | undefined false When ignoreErrors is true, do not print a warning message to the console if verification of assignment to process.env[name] fails.

Value Serialization

Values assigned to properties of process.env may only be strings. 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