read-env-file
Utilities for reading environment variable names & values from files in ".env" format
✔ Reads key/value pairs ✔ Handles commented & empty lines ✔ Allows spaces in quoted values ✔ Allows assignment operators in quoted values ✔ Reads from "./.env" when no path arg supplied ✔ Merges the results of multiple input files ✔ Invalid Format (missing key) ✔ Invalid Format (missing value) ✔ Invalid Format (missing assignment) ✔ Invalid Format (space in key) ✔ Invalid Format (space in unquoted value) ✔ Invalid Format (multiple assignment operators) ✔ Invalid Format Error contains accurate line number
Installation
yarn add read-env-file# or npm i read-env-file
Usage
Typescript-friendly (type declarations included)
# path/to/.envkey1=fookey2=bar
# path/.envkey1=foobarkey3=baz
// path/to/dir/index.jsconst readSingle readMultiple = ; ; // Attempts to read from ./.env ;// Promise<{key1: 'foo', key2: 'bar'}> readSingle;// {key1: 'foo', key2: 'bar'} ;// Promise<{key1: 'foobar', key2: 'bar', key3: 'baz'}> readMultiple;// {key1: 'foobar', key2: 'bar', key3: 'baz'}
File Formatting
Valid
- comments and blank lines are ignored
- values quoted (with
'
,"
, or backtick) to include spaces and=
character - spaces around keys and values are ignored
Examples:
key=value# comment starts with "#" (ignored) # whitespace is trimmed from keys and valueskey = valuekey =valuekey= value # whitespace in quoted values preservedkey="value with spaces' # Assignment operators in quoted values preservedkey="value=abc"
Invalid (throws Error)
Errors are informative and specify the cause, file, and line number:
Invalid file format at /some/path/.env:12
The following conditions cause an invalid format error:
Cause | Error Mssage |
---|---|
missing key | key undefined |
missing value | value undefined |
missing assignment | value undefined |
space in key | invalid spacing |
space in unquoted value | invalid spacing |
multiple assignment operators | multiple assignment operators |
Examples:
# missing key=value # missing valuekey= # missing assignmentkeyvalue # space in keyk e y = value # space in unquoted valuekey=value and words # multiple assignment operatorskey=value=invalid
Dependencies
None