In Javascript, I can access an environment variable like so:
pizza = process.env.PIZZA
Is there a simple syntax for throwing an error if that envar is missing/null/undefined? Something akin to Bash ?:
pizza = process.env.PIZZA? // not real Javascript
Yes, obviously I can just explicitly check myself if it's undefined:
pizza = process.env.PIZZA; if (!pizza) { throw ... }
But this gets repetitive very quickly. Every time I've ever want to access an envar, in any language, I want an error if that envar is missing. Before I write a little utility to do that check (my_env.require('PIZZA')), I'd like to be sure I'm not missing a Javascript feature that can easily achieve that.
Is there any simple language feature that can do this? Or perhaps a library that replaces process.env?
Helper function that throws if the environment variable doesn't exist:
function getEnv(name) {
let val = process.env[name];
if ((val === undefined) || (val === null)) {
throw ("missing env var for " + name);
}
return val;
}
Then in code you just say;
pizza = getEnv("pizza");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With