This document provides example usage of a customer logger, and integration with dotenv
.
For more examples, refer to the /example
directory.
If you need to filter env-var
logs based on log levels (e.g. trace logging only) or have your own preferred logger, you can use a custom logging solution such as pino
easily.
const pino = require('pino')()
const customLogger = (varname, str) => {
// varname is the name of the variable being read, e.g "API_KEY"
// str is the log message, e.g "verifying variable value is not empty"
log.trace(`env-var log (${varname}): ${str}`)
}
const { from } = require('env-var')
const env = from(process.env, {}, customLogger)
const API_KEY = env.get('API_KEY').required().asString()
You can optionally use dotenv with env-var.
- Just
npm install dotenv
and use it whatever way you're used to. - You can use
dotenv
withenv-var
via arequire()
call in your code; - Or you can preload it with the
--require
or-r
flag in thenode
CLI.
- The examples below assume you have a
.env
file in your repository and it contains a line similar toMY_VAR=a-string-value!
.
This is per the default usage described by dotenv
README.
// Read in the .env file
require('dotenv').config()
// Read the MY_VAR entry that dotenv created
const env = require('env-var')
const myVar = env.get('MY_VAR').asString()
This is per the preload section
of the dotenv
README.. Run the following code by using the
node -r dotenv/config your_script.js
command.
// This is just a regular node script, but we started it using the command
// "node -r dotenv/config your_script.js" via the terminal. This tells node
// to load our variables using dotenv before running the rest of our script!
// Read the MY_VAR entry that dotenv created
const env = require('env-var')
const myVar = env.get('MY_VAR').asString()
The other examples are available in the /example
directory.
catch-error.js
: demonstrates how you can use bluebird's custom catch functionality to respond to different error types.catch-error-promise.js
: same ascatch-error.promise.js
but with promises.custom-accessor.js
: demonstrates how you can build a custom accessor (e.g.asIntBetween()
) by composing internal accessors available atenv.accessors
, and attach it to theenv-var
instance.custom-accessor-2.ts
: Typescript version ofcustom-accessor.js
.logging.js
: self-explanatory.typescript.ts
: commonenv-var
usage in Typescript.