Node.js by Example: Environment Variables

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.

To set an environment variable, we can set the value on process.env. To read we look at the value of it on proces.env.

process.env.FOO = "1";
console.log("FOO:", process.env.FOO)
console.log("BAR:", process.env.BAR)

Use process.env to list all key/value pairs in the environment. This is how we return all the set keys

for (const [key] of Object.entries(process.env)) {
    console.log(key);
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

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

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

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
...

Next example: .