@karmaniverous/get-dotenv

3.1.19 • Public • Published

get-dotenv

Load environment variables with a cascade of environment-aware dotenv files. You can:

  • Load dotenv files synchronously or asynchronously.
  • Load variables for a specific environment or none.
  • Define dynamic variables progressively in terms of other variables and other logic.
  • Exclude public, private, global, environment-specific, or dynamic variables.
  • Specify explicit variables to include.
  • Extract the resulting variables to an object, process.env, a dotenv file, or a logger object, in any combination.
  • Execute a shell command within the resulting environment. You can even nest additional getdotenv calls!
  • Specify the directories containing your dotenv files.
  • Specify the filename token that identifies dotenv files (e.g. '.env').
  • Specify the filename extension that identifies private variables (e.g. 'local').
  • Set defaults for all options in a getdotenv.config.json file in your project root directory.
  • Generate a custom getdotenv-based CLI for use in your own projects.

getdotenv relies on the excellent dotenv parser and uses dotenv-expand for recursive variable expansion.

The command-line version populates process.env from your dotenv files (you can also specify values inline) and can then execute a shell command within that context. Any child getdotenv instances will inherit as defaults the parent shell's environment and optionally its getdotenv settings.

You can always use getdotenv directly on the command line, but its REAL power comes into play when you use it as the foundation of your own CLI. This lets you set defaults globally and configure pre- and post-hooks that mutate your getdotenv context and do useful things like grab an AWS session from your dev environment and add it to the command execution context.

When you plug your own commander CLI commands into the getdotenv base, they will execute within all of the environmental context created above!

Installation

npm install @karmaniverous/get-dotenv

Usage

import { getDotenv, getDotenvSync } from '@karmaniverous/get-dotenv';

// asynchronous
const dotenv = await getDotenv(options);

// synchronous
const dotenvSync = await getDotenvSync(options);

See OptionsType below for configuration options.

Dynamic Processing

This package supports the full dotenv-expand syntax.

Yse the dynamicPath option to add a relative path to a Javascript file with a function expression like this:

(dotenv) => ({
  SOME_DYNAMIC_VARIABLE: (dotenv) => someLogic(dotenv),
  ANOTHER_DYNAMIC_VARIABLE: (dotenv) =>
    someOtherLogic(dotenv.SOME_DYNAMIC_VARIABLE),
});

This function should take the expanded dotenv object as an argument and return an object. Each object key will be evaluated progressively.

If the corresponding value is a function, it will be executed with the current state of dotenv as its single argument and the result applied back to the dotenv object. Otherwise, the value will just be applied back to dotenv.

Since keys will be evaluated progressively, each successive key function will have access to any previous ones. These keys can also override existing variables.

More to Come!

Implementation always runs a little behind documentation. These topics & improvements are coming soon:

  • An example of dotenv-based environment config.
  • Integrating getdotenv into your npm scripts.
  • Creating a getdotenv-based CLI.
  • Some gotchas & tips around managing your shell execution context.

Command Line Interface

Note that the defaults below can be changed in your own environment by deriving your base CLI using the getDotenvCli function or placing a getdotenv.options.json file in your project root directory.

Usage: getdotenv [options] [command]

Base CLI.

Options:
  -e, --env <string>                  target environment
  -v, --vars <string>                 dotenv-expanded delimited key-value pairs: KEY1=VAL1 KEY2=VAL2 (default: "")
  -c, --command <string>              dotenv-expanded shell command string
  -o, --output-path <string>          consolidated output file, follows dotenv-expand rules using loaded env vars
  -p, --load-process                  load variables to process.env ON (default)
  -P, --load-process-off              load variables to process.env OFF
  -a, --exclude-all                   exclude all dotenv variables from loading ON
  -A, --exclude-all-off               exclude all dotenv variables from loading OFF (default)
  -z, --exclude-dynamic               exclude dynamic dotenv variables from loading ON
  -Z, --exclude-dynamic-off           exclude dynamic dotenv variables from loading OFF (default)
  -n, --exclude-env                   exclude environment-specific dotenv variables from loading
  -N, --exclude-env-off               exclude environment-specific dotenv variables from loading OFF (default)
  -g, --exclude-global                exclude global dotenv variables from loading ON
  -G, --exclude-global-off            exclude global dotenv variables from loading OFF (default)
  -r, --exclude-private               exclude private dotenv variables from loading ON
  -R, --exclude-private-off           exclude private dotenv variables from loading OFF (default)
  -u, --exclude-public                exclude public dotenv variables from loading ON
  -U, --exclude-public-off            exclude public dotenv variables from loading OFF (default)
  -l, --log                           console log loaded variables ON
  -L, --log-off                       console log loaded variables OFF (default)
  -d, --debug                         debug mode ON
  -D, --debug-off                     debug mode OFF (default)
  --default-env <string>              default target environment (default: "dev")
  --dotenv-token <string>             dotenv-expanded token indicating a dotenv file (default: ".env")
  --dynamic-path <string>             dynamic variables path (default: "./env/dynamic.js")
  --paths <string>                    dotenv-expanded delimited list of paths to dotenv directory (default: "./ ./env")
  --paths-delimiter <string>          paths delimiter string (default: " ")
  --paths-delimiter-pattern <string>  paths delimiter regex pattern (default: "\\s+")
  --private-token <string>            dotenv-expanded token indicating private variables (default: "local")
  --vars-delimiter <string>           vars delimiter string (default: " ")
  --vars-delimiter-pattern <string>   vars delimiter regex pattern (default: "\\s+")
  --vars-assignor <string>            vars assignment operator string (default: "=")
  --vars-assignor-pattern <string>    vars assignment operator regex pattern (default: "=")
  -h, --help                          display help for command

Commands:
  cmd                                 execute shell command string (default command)
  help [command]                      display help for command

API Documentation

Functions

getDotenv([options])Promise.<object>

Asynchronously process dotenv files of the form .env[.][.]

getDotenvSync([options])Object

Synchronously process dotenv files of the form .env[.][.]

getDotenvCli([options])object

Generate a CLI for get-dotenv.

Typedefs

GetDotenvOptions : Object

get-dotenv options type

GetDotenvPreHookCallbackGetDotenvCliOptions

GetDotenv CLI Pre-hook Callback type. Transforms inbound options & executes side effects.

GetDotenvPostHookCallback : function

GetDotenv CLI Post-hook Callback type. Executes side effects within getdotenv context.

getDotenv([options]) ⇒ Promise.<object>

Asynchronously process dotenv files of the form .env[.][.<PRIVATE_TOKEN>]

Kind: global function
Returns: Promise.<object> - The combined parsed dotenv object.

Param Type Description
[options] GetDotenvOptions options object

getDotenvSync([options]) ⇒ Object

Synchronously process dotenv files of the form .env[.][.]

Kind: global function
Returns: Object - The combined parsed dotenv object.

Param Type Description
[options] GetDotenvOptions options object

getDotenvCli([options]) ⇒ object

Generate a CLI for get-dotenv.

Kind: global function
Returns: object - The CLI command.

Param Type Description
[options] object options object
[options.alias] string cli alias (used for cli help)
[options.command] string dotenv-expanded shell command string
[options.debug] bool debug mode
[options.defaultEnv] string default target environment
[options.description] string cli description (used for cli help)
[options.dotenvToken] string dotenv-expanded token indicating a dotenv file
[options.dynamicPath] string path to file exporting an object keyed to dynamic variable functions
[options.excludeDynamic] bool exclude dynamic dotenv variables
[options.excludeEnv] bool exclude environment-specific dotenv variables
[options.excludeGlobal] bool exclude global dotenv variables
[options.excludePrivate] bool exclude private dotenv variables
[options.excludePublic] bool exclude public dotenv variables
[options.loadProcess] bool load variables to process.env
[options.log] bool log result to console
[options.logger] function logger function
[options.outputPath] string consolidated output file, dotenv-expanded using loaded env vars
[options.paths] string dotenv-expanded delimited list of input directory paths
[options.pathsDelimiter] string paths delimiter string
[options.pathsDelimiterPattern] string paths delimiter regex pattern
[config.preHook] GetDotenvPreHookCallback transforms cli options & executes side effects
[options.privateToken] string dotenv-expanded token indicating private variables
[config.postHook] GetDotenvPostHookCallback executes side effects within getdotenv context
[options.vars] string dotenv-expanded delimited list of explicit environment variable key-value pairs
[options.varsAssignor] string variable key-value assignor string
[options.varsAssignorPattern] string variable key-value assignor regex pattern
[options.varsDelimiter] string variable key-value pair delimiter string
[options.varsDelimiterPattern] string variable key-value pair delimiter regex pattern

GetDotenvOptions : Object

get-dotenv options type

Kind: global typedef
Properties

Name Type Description
[defaultEnv] string default target environment
[dotenvToken] string token indicating a dotenv file
[dynamicPath] string path to file exporting an object keyed to dynamic variable functions
[env] string target environment
[excludeDynamic] bool exclude dynamic variables
[excludeEnv] bool exclude environment-specific variables
[excludeGlobal] bool exclude global & dynamic variables
[excludePrivate] bool exclude private variables
[excludePublic] bool exclude public variables
[loadProcess] bool load dotenv to process.env
[log] bool log result to logger
[logger] function logger object (defaults to console)
[outputPath] string if populated, writes consolidated .env file to this path (follows dotenv-expand rules)
[paths] Array.<string> array of input directory paths
[privateToken] string token indicating private variables
[vars] object explicit variables to include

GetDotenvPreHookCallback ⇒ GetDotenvCliOptions

GetDotenv CLI Pre-hook Callback type. Transforms inbound options & executes side effects.

Kind: global typedef
Returns: GetDotenvCliOptions - transformed GetDotenv CLI Options object (undefined return value is ignored)

Param Type Description
options GetDotenvCliOptions inbound GetDotenv CLI Options object

GetDotenvPostHookCallback : function

GetDotenv CLI Post-hook Callback type. Executes side effects within getdotenv context.

Kind: global typedef

Param Type Description
dotenv object dotenv object

See more great templates and other tools on my GitHub Profile!

Package Sidebar

Install

npm i @karmaniverous/get-dotenv

Weekly Downloads

1,325

Version

3.1.19

License

BSD-3-Clause

Unpacked Size

73.7 kB

Total Files

17

Last publish

Collaborators

  • karmaniverous