Menu
CoddyTech

Environment Variables

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 5 of 24.

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, so ?? gives it a default.

// 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
  • list prints a heading first: Notes for <NOTES_OWNER>, or Notes for you when the variable is not set.
  • No notes yet stays on the next line.

Run node notes.js list. The checks also run it as 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