简体   繁体   中英

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 ?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM