1 minute read

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.

Exercise

Exercise:

Write a plain JavaScript file that reads in an environmental variable from a .env file using the dotenv library.

Detailed instructions:

  • Create a new folder called practice-dotenv
  • Enter the folder practice-dotenv
  • Install dotenv with npm
  • a new .env file and populate it with the variable FOO=BAR
  • Create a new file main.js and have it read in the variables in .env using the dotenv library

Solution

mkdir practice-dotenv
cd practice-dotenv
npm i dotenv

Create a new file .env with these contents. Notice that there are no spaces around =.

FOO=BAR

Create a new file called main.js with the following contents.

require('dotenv').config();
console.log(process.env.FOO);

When we run it, this should be the expected output.

$ node main.js
BAR

Closing remarks

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.

Subscribe

Comments