1.0.2 • Published 6 years ago

@camsmith145/env v1.0.2

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

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

ParameterTypeDescription
pathstring | undefinedAbsolute or relative path to a file. Defaults to ./.env
optionsObjectA few modifications to the behavior

Path Resolution

Base of path Parameter ValueMethod of importExpected File Content
undefinedJSON.parse(/* content of ./.env */)Serialized JSON object
.envJSON.parse(/* content of ./.env */)Serialized JSON object
.env.jsonJSON.parse(/* content of ./.env.json */)Serialized JSON object
.env.jsJSON.parse(/* content of ./.env.js */)JS module exports Object

Options Object

PropertyTypeDefaultDescription
ignoreErrorsboolean | undefinedfalseDo not throw an Error if verification of variable assignment to process.env[name] fails.
yieldExistingboolean | undefinedfalseDo not overwrite existing environment variables of the same name. (Sets ignoreErrors to true)
suppressWarningsboolean | undefinedfalseWhen 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