Home > OS >  Trying to extract the process.env values that I need if they exist
Trying to extract the process.env values that I need if they exist

Time:01-21

I have validation logic to check if the process.env variables I need exist.

const example1 = process.env.example1
const example2 = process.env.EXAMPLE_2
const example3 = process.env.EXAMPLE_3

const msg = 'Missing a process.env value, name: '
if (!example1) throw new Error(`${msg} ${example1}`)
if (!example2) throw new Error(`${msg} ${example2}`)
if (!example3) throw new Error(`${msg} ${example3}`)

This goes on for roughly 50-60 env vars. I'd love to be able to pass a function process.env and return an object that contains the values if they exist. Does anybody have any ideas?

CodePudding user response:

.env

VAR1=1
VAR2=
#VAR3=
VAR4=4
VAR5=5

app.js

require('dotenv').config();

const neededVars = ['VAR1', 'VAR2', 'VAR3'];


function check(vars) {
    vars.map(key => {
        if (!process.env[key])
            throw new Error(`Missing a process.env value, name: ${key}`)
    })
}

check(neededVars);
  • Related