@ifaxity/env
The minimal enviroment variable package for modern Node.js environments. No dependencies.
Node 6 or above is required as ES6 is needed.
Code heavily based on dotenv package on npm
Installation
npm install @ifaxity/env --save
or if you use yarn
yarn add @ifaxity/env
Usage
To use the module just require it like this
const env = require('@ifaxity/env');
API
Example .env file:
NODE_ENV=production
DB_HOST='localhost'
DB_PORT=27017
PI=3.14
DEBUG=true
MULTILINE="Hello\nWorld!"
The module is a proxy object so you can use this to get an environment variable and also convert it to the correct type. As node.js doesn't support process.env
to have any other values other than strings for now.
Types parsed are limited to boolean, number, string
for now.
If the variable doesnt exist then null
is returned.
Like this:
Consider the variables in the example file above
const env = require('@ifaxity/env');
env.NODE_ENV
env.PORT
env.BOOL
const { NODE_ENV, PORT, TRUE } = require('@ifaxity/env');
However parse
& config
is reserved as functions in this module.
Configures and loads the environment variables from a file.
Returns the parsed variables in a form of an object.
However unlike the module these variables are not proxied.
Parameters
Basic Usage
const env = require('@ifaxity/env');
env.config();
const envVars = env.config({
path: __dirname,
env: {},
});
Parses a key=value pair string to an object of variables
Returns an object of the key=value
pairs of the data
Parameters
- data {String} - Data to parse in a
key=value
pair format.
Basic Usage
const env = require('@ifaxity/env');
const envVars = env.parse(fs.readFileSync(process.cwd() + '/.env', 'utf8'));