Env utility
by Nicholas C. Zakas
If you find this useful, please consider supporting my work with a donation.
Description
A utility for verifying that environment variables are present in Node.js. The main use case is to easily throw an error when an environment variable is missing. This is most useful immediately after a Node.js program has been initiated, to fail fast and let you know that environment variables haven't been setup correctly.
Usage
Node.js
Install using [npm][npm] or [yarn][yarn]:
npm install @humanwhocodes/env --save
# or
yarn add @humanwhocodes/env
Import into your Node.js project:
const { Env } = require("@humanwhocodes/env");
import { Env } from "@humanwhocodes/env";
By default, an Env
instance will read from process.env
.
Deno
Import into your Deno project:
import { Env } from "https://unpkg.com/@humanwhocodes/env/dist/env.js";
By default, an Env
instance will read from Deno.env()
.
Browser
It's recommended to import the minified version to save bandwidth:
import { Env } from "https://unpkg.com/@humanwhocodes/env/dist/env.min.js";
However, you can also import the unminified version for debugging purposes:
import { Env } from "https://unpkg.com/@humanwhocodes/env/dist/env.js";
By default, an Env
instance will read from an empty object.
API
After importing, create a new instance of Env
to start reading environment variables:
const env = new Env();
const username = env.get("USERNAME");
const username = env.get("USERNAME", "humanwhocodes");
const username = env.require("USERNAME");
You can also specify an alternate object to read variables from. This can be useful for testing or in the browser (where there is no environment variable to read from by default):
const env = new Env({
USERNAME: "humanwhocodes"
});
const username = env.get("USERNAME");
const username = env.require("PASSWORD");