パッケージの詳細

nvar

sneakertack16.8kMIT1.3.1

Reads shell environment variables from a file and assigns them to process.env (or anywhere else).

env, environment, variable, dotenv

readme

Build Status A static test-count badge (dynamise one day) Coverage Status

Intro

nvar is a Node module that lets you declare environment variables in an envfile (usually .env in your app's root folder). When your app starts, nvar loads those variables (into process.env by default), making it useful for editing your app configuration and API credentials during development.

It works like (and is inspired by) dotenv (Ruby), dotenv (Node), and env2. It differs from the popular dotenv library for Node in that nvar follows Shell syntax (so if you are already loading environment variables via source, you can expect this module to work like a drop-in replacement).

Usage

Install by running:

npm install --save nvar

Make a .env file in your app's root folder:

# .env (usually added to .gitignore)
DB_URL='postgresql://user:password@localhost:5432/mydb'
GITHUB_API_TOKEN=6495e6cf5fb93d68 # quotes are usually optional.
export LOGLEVEL=SEVERE # prepend with 'export' (not required for nvar, but typically found in Bash scripts).

Then, require and call nvar at the top of your application code:

// Note the calling brackets at the end.
require('nvar')();

// Variables that were declared in .env in the application's root folder have now been added to process.env.
console.log(process.env.DB_URL); // Prints 'postgresql://user:password@localhost:5432/mydb'.
console.log(process.env.GITHUB_API_TOKEN); // Prints '6495e6cf5fb93d68'.
console.log(process.env.LOGLEVEL); // Prints 'SEVERE'.

Or, if your .env file is somewhere else, then do:

require('nvar')('../somedir/my-env.sh')

Or, if you need to change some other options from the defaults, then do:

require('nvar')({
  // All options listed.
  path: '../somedir/set-env.sh', // Filepath to envfile
  source: 'FOO=BAR', // Alternatively, provide the envfile source directly.
  target: module.exports, // Assign to something else besides process.env instead.
  enoent: 'warn', // What should happen if the envfile was not found? Set to null|'warn'|'error'.
  override: 'all' // Whether to override pre-existing variables. Set to 'all'|'empty'|'none'.
});

Writing your envfile

The TL;DR version: Write lines of KEY='VALUE'. No spaces before/after the =. Single-quote your values (and if you need a single-quote literal, escape with '\'').

FOO='bar'
ENVIRONMENT='development'
API_TOKEN='12345abc'
GREETING='What'\''s your name?'

The in-depth version: The following shell-isms are supported, so its very likely that you can use nvar to read your existing Bash-sourced envfile, and vice versa.

FOO=bar
EGGS=halfboiled TOAST=kaya # Multiple assignments on the same line work.
LUNCH=noodle echo ignored # Disregards shell commands.

# Backslash followed by newline breaks the value across multiple lines.
pi=3.141\
59265359

# Prepend with 'export', nvar doesn't mind.
export gum=secretly
export buns=quietly
# If all your variables are prepended with 'export', then `source`ing your envfile vs. using nvar would do the same thing, so that's convenient.

# Things like '\', '$', and whitespace do special things in shell. To prevent, a safe choice is single-quotes, which literalizes almost everything.
statement='everything i$ literal,
including newlines,
so that'\''s okay.' # Escape single-quotes by writing '\''.

# Double quotes: Mostly like single-quotes, though parameter expansion still works. See further below.
VERDICT="we've decided
that this is pretty !@#\$-ing \"cool\"." # Escape ", $, and \ with a backslash.

# Concatenation
FILLERS="foo"bar'baz' # Sets a value of 'foobarbaz' (FYI: concatenation is really why '\'' works as an escape when single-quoting).

# Parameter expansion of prior variables.
DB_USER=alice
DB_PASS=in
DB_HOST=data.land
DB_PORT=5432
DB_NAME=fun
DB_URL="${DB_USER}:${DB_PASS}@$DB_HOST:$DB_PORT/${DB_NAME}" # Curly braces are optional. Can be done within double quotes, or unquoted.

Feel free to review the test results, which also doubles as a specification for the syntax that can be accepted by the module.

API

Here is a list of options you can pass in as an options object to nvar:

Options

Option Default Description
path v1.0 './.env' Location of the envfile to load. If you only want to change this filepath, you can pass it directly as a string argument, instead of wrapping it in an options object.
source v1.0 null Alternatively, pass in the assignments directly as text, e.g. 'EGGS=halfboiled\nTOAST=kaya'. path is ignored if source is set.
target v1.0 process.env Where to save the assignments to.
enoent v1.1 'warn' if relying on default path, 'error' if path was specified Whether to throw an error, log a warning to stderr, or do nothing if the file was not found. Irrelevant if using source instead of path.
override v1.3 'all' If a variable already exists in the environment, should nvar override it? 'all' means the environment can be overriden (default). 'empty' means only empty '' or unset variables can be set. 'none' means only unset variables can be set.

Advanced needs: Need even more control? Pass in a custom function (params (key, env)) that returns true or false instead. E.g. setting override to (key) => !/[A-Z]/.test(key) overrides variables written in lowercase only.

Contributing

Where possible, this module tries to support all shell syntax that might reasonably be expected to appear in a config file. If you believe you have a use case that is not covered, feel free to raise an issue.

更新履歴

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[Unreleased]

[1.3.1] - 2018-04-27

Fixed

[1.3.0] - 2018-02-20

Added

  • Add override configuration option, which controls whether variables that are already pre-existing in the environment should be overriden or not.

[1.2.4] - 2017-08-19

Changed

  • Adjusted test script commands.

Fixed

  • Restore running of tests on Travis CI (broken since ad42abd532d1628c75b6f9bddeca36181c3846a3).

[1.2.3] - 2017-08-07

Added

  • Add a copy of the most recent tests results to tests/.
  • Include license file with the repository.

[1.2.2] - 2017-08-04

Added

  • Add integration with Coveralls.
  • Add an overall functional test.

Changed

  • Throw an error if the module encounters an unexpected character during variable declaration.

[1.2.1] - 2017-08-03

Added

  • API section in the readme, which details options and defaults.

Removed

  • Made package slightly leaner by removing tests and metafiles during install.

[1.2.0] - 2017-08-02

Added

  • Support Node.js runtimes down till v0.10.0 (via transpilation down to ES5 during install, runtimes >= v6 will still load the ES2015+ source directly).

Changed

  • Module no longer depends on fs until it needs to load a file.

[1.1.0] - 2017-08-01

Added

  • Add enoent option, to specify whether to throw, warn, or do nothing if the envfile was not found. The default is to warn if no path was specified (defaulting to .env), and throw if a path was explicitly specified.
  • Add a basic Travis configuration.
  • Add words to readme.

Changed

  • nvar will only warn and no longer throw an error by default when called in its simplest form (i.e. require('nvar')() without any arguments) and a .env envfile was not found.

[1.0.3] - 2017-07-30

Fixed

  • Implement string argument shorthand that was advertised in readme but overlooked during development.

[1.0.2] - 2017-07-30

Added

  • This changelog, with descriptions starting from v1.0.0.

[1.0.1] - 2017-07-28

Changed

  • Minor touchup to Readme only.

[1.0.0] - 2017-07-27

Added

  • Initial release. It supports:
    • Reading configuration from a file path (./.env by default), or directly passed in as source.
    • Assignment to any arbitrary target (process.env by default).
    • Parsing support for the following shell-isms:
      • Unquoted values
      • Optional 'export' prefixes.
      • Comments with #.
      • Single-quoted values (Strong quoting)
      • Double-quoted values (Weak quoting)
      • Backslash-newline line splitting
      • Backslash-escaping of special characters
      • Parameter expansion