Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how can I throw an error if an environmental variable is missing?

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?

like image 572
Sasgorilla Avatar asked Nov 03 '25 13:11

Sasgorilla


1 Answers

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");
like image 85
selbie Avatar answered Nov 06 '25 03:11

selbie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!