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.

// In Node.js, we use the 'process' object to interact with environment variables

// To set a key/value pair, we can use process.env
process.env.FOO = '1';

// To get a value for a key, we also use process.env
console.log("FOO:", process.env.FOO);
console.log("BAR:", process.env.BAR);

// To list all key/value pairs in the environment
console.log("\nAll environment variables:");
Object.keys(process.env).forEach((key) => {
    console.log(key);
});

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.

$ node environment-variables.js
FOO: 1
BAR: undefined

All environment variables:
TERM_PROGRAM
PATH
SHELL
...
FOO

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.

$ BAR=2 node environment-variables.js
FOO: 1
BAR: 2
...

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.