I use this snippet to find out if the environment variable is set
if ('DEBUG' in process.env) { console.log("Env var is set:", process.env.DEBUG) } else { console.log("Env var IS NOT SET") }
Theoretical notes
As stated in NodeJS 8 docs :
The process.env property returns an object containing the user environment. See environment (7) .
[...]
Assigning a property in process.env implicitly converts the value to a string.
process.env.test = null console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined'
Although, when the variable is not set in the environment, the corresponding key is generally absent in the process.env object, and the corresponding process.env property is undefined .
Here is another example (remember the quotation marks used in this example):
console.log(process.env.asdf, typeof process.env.asdf) // => undefined 'undefined' console.log('asdf' in process.env) // => false // after touching (getting the value) the undefined var // is still not present: console.log(process.env.asdf) // => undefined // let set the value of the env-variable process.env.asdf = undefined console.log(process.env.asdf) // => 'undefined' process.env.asdf = 123 console.log(process.env.asdf) // => '123'
Additional Code Style Information
It is worth mentioning that the original question:
How can I check if the environment variable is set in Node.js?
already contains the answer. To ensure that markup is added:
How can I [check if] an [env var] [is set] in [Node.js]?
Now literally translate this into JavaScript:
if ('env_var' in process.env)
Where:
[check if] = if[env var] = 'env_var'[is set] = in[Node.js environment] = process.env
Simple and clear.
maxkoryukov
source share