Menu
CoddyTech

Environment Variables

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 6 of 33.

Some settings belong to the person running a program, not to the words they type after it.

Environment variables are named strings the shell hands to every program. Node puts them in process.env. An unset variable is undefined. a ?? b gives a, unless a is undefined or null; then it gives b. So process.env.CITY ?? 'Lisbon' is 'Lisbon' when CITY is not set.

// CITY=Oslo node weather.js
const city = process.env.CITY ?? 'Lisbon';
console.log(`Weather for ${city}`);

On a laptop you set one for a single run by writing it before the command: CITY=Oslo node weather.js prints Weather for Oslo, and plain node weather.js prints Lisbon. Names are case sensitive. The terminal beside your code sets no variables, so it always shows the default.

challenge icon

Challenge

Easy

Your notes should name the person they belong to. The name comes from an environment variable, a named setting the shell hands to the program, not from the words typed after the command.

  1. In notes.js, in the list branch, read the environment variable NOTES_OWNER.
  2. Before No notes yet, print a heading line: Notes for followed by the owner's name. When NOTES_OWNER is not set, use the word you instead of a name.

With NOTES_OWNER set to Ada, list prints:

Notes for Ada
No notes yet

With no NOTES_OWNER, it prints:

Notes for you
No notes yet

The other commands do not change.

Try it: type list in the box after $ node notes.js and press Enter. You see Notes for you, then No notes yet. The terminal here cannot set environment variables, so you always see you. When you press Check, the checks also run list with NOTES_OWNER set to Ada and to Grace, and expect Notes for Ada and Notes for Grace. On a laptop you would try it with NOTES_OWNER=Ada node notes.js list.

Try it yourself

// Your notes tool starts here.
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

if (command === 'add') {
    console.log(`Adding: ${text}`);
} else if (command === 'list') {
    console.log('No notes yet');
} else {
    if (command) {
        console.error(`Unknown command: ${command}`);
    }
    console.error('Usage: node notes.js <command> [words]');
    process.exit(1);
}

All lessons in Node.js Basics

Practice on your own: Express playground