Programming exercise: reading in environmental variables with dotenv
Programming, as a craft, is funny. Compared to other crafts, like professional musicians, programmers don’t seem to deliberately practice their craft.
I would argue that it is pretty noncontroversial to say that if you want to get better at something, you must practice. So if we want to become better programmers, we must practice programming!
In this exercise you learn how to read in a single environmental variable and output its contents to stdout. Repeat 5 times.
.env file using the dotenv library.
- Create a new folder called
- Enter the folder
- a new
.envfile and populate it with the variable
- Create a new file
main.jsand have it read in the variables in
mkdir practice-dotenv cd practice-dotenv npm i dotenv
Create a new file
.env with these contents. Notice that there are no spaces
Create a new file called
main.js with the following contents.
When we run it, this should be the expected output.
$ node main.js BAR
This exercise sounds trivial. Perhaps it is. Yet, if it is really this trivial, can you do it? Can you do it without peeking at the solution?
Do you really know how to do this? Or do you think you know it?
The first time I did this exercise without looking at the solution I tried to
console.log(NAME)! This is wrong! The correct solution is
console.log(process.env.NAME). I thought I knew, but I didn’t! This
exercise poked a hole right through my veil of ignorance.
Please try out the exercise and let me know in the comments what you think of it! I’d love to hear your feedback on this piece.