1.0.5 • Published 4 years ago
@gabrielmethot/node-env-parser v1.0.5
node-env-parser
Utility functions to parse Node.js-like environment variables to type-checked values.
import { EnvironmentParser } from "@gabrielmethot/node-env-parser";
process.env = {
VERSION: "2.1",
TOGGLE_FEATURE: "true",
};
const parser = new EnvironmentParser(process.env);
const NODE_ENV: string = parser.parseString("NODE_ENV", {
default: "development",
});
const VERSION: number = parser.parseNumber("VERSION", {
default: 1,
parser: (value) => parseFloat(value),
});
const TOGGLE_FEATURE: boolean = parser.parseBoolean("TOGGLE_FEATURE");
// { NODE_ENV: "development", VERSION: 2.1, TOGGLE_FEATURE: true }
console.log({ NODE_ENV, VERSION, TOGGLE_FEATURE });
Installing
$ npm install @gabrielmethot/node-env-parser
Error handling
If an environment variable is defined, then it must be a string that can be parsed using the provided parsing function. Otherwise, it throws an error.
import { EnvironmentParser } from "@gabrielmethot/node-env-parser";
process.env = {
TOGGLE_FEATURE_A: "true",
TOGGLE_FEATURE_B: "No Thanks!",
};
const parser = new EnvironmentParser(process.env);
parser.parseBoolean("TOGGLE_FEATURE_A"); // Returns true
parser.parseBoolean("TOGGLE_FEATURE_B"); // Throws a ConversionError
If an environment variable is undefined, then a default value must be provided. Otherwise, it throws an error.
import { EnvironmentParser } from "@gabrielmethot/node-env-parser";
process.env = {};
const parser = new EnvironmentParser(process.env);
parser.parseString("SOME_VALUE", { default: "Hello World!" }); // Returns "Hello World!"
parser.parseString("SOME VALUE"); // Throws a UndefinedError
About this repository
Scripts
Launch CJS build
npm run build:cjs
Launch ESM build
npm run build:esm
Launch all builds
npm run build
Start an example Node.js app (requires CJS build)
npm run example:node
Start an example web app (requires ESM build)
npm run example:web
Detect TypeScript errors
npm run typecheck
Detect problematic coding patterns
npm run lint
Detect and attempt to fix problematic coding patterns
npm run lint:fix
Detect inconsistent code style
npm run format
Detect and fix inconsistent code style
npm run format:fix
Run unit tests
npm test
Prepare package for publication
npm run prepublishOnly