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
EasyYour 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.
- In
notes.js, in thelistbranch, read the environment variableNOTES_OWNER. - Before
No notes yet, print a heading line:Notes forfollowed by the owner's name. WhenNOTES_OWNERis not set, use the wordyouinstead of a name.
With NOTES_OWNER set to Ada, list prints:
Notes for Ada
No notes yetWith no NOTES_OWNER, it prints:
Notes for you
No notes yetThe 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
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommandsPractice on your own: Express playground