Start learning free

LESSON 148 OF 173 · BACKEND: SHIPPING IT

Settings from the Environment

Practice

The shop's code is the same on your computer and on the server, but a few settings differ: the port it listens on, and where the database file is. Don't write them into the code. The server hands them to the program as environment variables: named text values that every program it starts can read.

In Node.js they are in the object process.env. process.env.NAME gives you a variable's text, or undefined when it isn't set, and || then gives the default written on its right. The values are always text, so a number needs Number(). For example, a script that reads how many times to retry and how to greet:

const retries = Number(process.env.RETRIES || "3");
const greeting = process.env.GREETING || "Hello";

Your file prints the settings the server would use. Then the check calls your loadSettings() three times, with different variables set, and prints what it returns:

Port: 8000
Database: shop.db
Nothing set (your computer):
{'port': 8000, 'database_path': 'shop.db'}
PORT=5000 and DATABASE_PATH=/data/shop.db (the server):
{'port': 5000, 'database_path': '/data/shop.db'}
Only PORT=10000:
{'port': 10000, 'database_path': 'shop.db'}

Your task: write loadSettings(). It reads PORT as a number, with the default "8000", and DATABASE_PATH, with the default "shop.db", and returns them in an object with the keys port and database_path. Below it, call it once and print the two settings after Port: and Database:.


Assignment
Follow the Coding Tutorial to read PORT and DATABASE_PATH from the environment with defaults, return them in an object, and print the settings the server would use.


Hint
|| gives the value on its right when the variable is undefined. Put the port inside Number( ), but not the path: a path is text. Without a return, the check prints undefined.


STEP 1 OF 7
    Ctrl + Enter to check