Environment Variables in JavaScript
Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in JavaScript.
To set a key/value pair, we directly assign to process.env
. To get a value for a key, we access it from process.env
. If the key isn’t present in the environment, it will return undefined
.
We can use Object.keys(process.env)
to get all the keys in the environment. Here we print all the keys.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is undefined.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
Note that in Node.js, environment variables are strings by default. If you need to work with other types, you’ll need to parse the values accordingly.