1.0.6 • Published 5 years ago

@poppinss/env v1.0.6

Weekly downloads
7
License
MIT
Repository
github
Last release
5 years ago

Env

circleci-image npm-image license-image

Environment variables parser and reader for Node.js. This module parses the raw string in dotfile format and set process.env variables from it. Also, you can make use of bash like syntax for variable interpolation.

Table of contents

Usage

Install the package from npm as follows:

npm i @poppinss/env

# yarn
yarn add @poppinss/env

and then use it as follows

import { env } from '@poppinss/env'

env.process(`
  PORT=3333
  HOST=127.0.0.1
`)

and then read the values as follows

env.get('PORT')

// or
process.env.PORT

The Env.process method will not overwrite the existing environment variables (that is how it should be). However, if you want to overwrite existing values, maybe inside testing environment, then you can call the process method as follows:

env.process('PORT=3333', true)

Casting values

The values saved as environment variables are always string. However, this module does the values casting for you, when you read them using Env.get.

env.process(`
  CACHE_VIEWS=false
`)

process.env.CACHE_VIEWS // string
env.get('CACHE_VIEWS') // boolean

Following values are casted

.env ValueCasted value
'null'null
'true'true
'1'true
'false'false
'0'false

Variable interpolation

You can also reference environment variables by using bash like interpolation syntax.

env.process(`
  HOST=localhost
  PORT=3333
  URL=$HOST:$PORT
`)

All letter, numbers and _ after the dollar sign will be considered as a variable reference. Any other characters apart from the above mentioned aren't allowed. However, you can wrap your variable substitution inside curly braces {} when using characters other than the whitelisted one's.

Following will fail

The following reference to $REDIS-USER will fail, since the parser will stop at - and consider USER as a static string.

env.process(`
  REDIS-USER=foo
  REDIS-URL=localhost@$REDIS-USER
`)

Do this instead

The usage of curly braces {} tells the parser to parse until the closing brace.

env.process(`
  REDIS-USER=foo
  REDIS-URL=localhost@${REDIS-USER}
`)

Escape characters

Quite often, you will have strings where you want the $ dollar character to be considered as a literal value. In that case you can escape the character as follows.

env.process(`
  PASSWORD=pa\\$\\$word
`)

process.env.PASSWORD // pa$$word

DO NOTE: The usage of double escape \\ is required when you are typing the string directly in Javascript, since the first escape is swallowed by JS. However, if you are writing the enviornment variables inside the .env file, then a single escape \ is required.

API

Following are the autogenerated files via Typedoc

Maintainers

Harminder virk

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago