castenv
v0.1.18
Published
Automatically cast process.env environment variables into native types (boolean, number, json object)
Downloads
10
Readme
castenv
Overview
Environment variables like MAX_THREADS=5
, ENABLE_DEBUG=false
are usually imported into process.env as strings.
This leads to subtle bugs when treating them like booleans or numbers e.g. if (process.env['ENABLE_DEBUG'])...
because "false" equals true in JS
castenv
uses JSON.parse() to convert env variables into native types. castenv.cast()
will modify process.env,
and castenv.env()
will leave process.env unmodified.
Getting Started
Install it via npm:
npm install castenv
Include in your project:
// cast process.env in place
require("castenv").cast()
// alternatively, don't modify process.env
var env = require("castenv").env()
Example Casting
process.env["TEST_NUMBER_VALUE"] = "5"
console.log(typeof process.env["TEST_NUMBER_VALUE"])
// "string"
require("castenv").cast()
console.log(typeof process.env["TEST_NUMBER_VALUE"])
// number
Pitfalls
- hex & octal values like
0x123
and0123
will return as strings--JSON doesn't support those literals
License
MIT