CodePark/ questions / Linux commands & permissions
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Linux commands & permissions

You run these two lines in a shell, and process.env.PORT is undefined inside the app. Why?

PORT=4000
node server.js
PORT=4000 created a shell variable that isn't exported, so child processes don't inherit it

PORT=4000 on its own line creates a shell variable, but it does not export it. A child process gets a copy of its parent's environment, and the environment only holds exported variables. So Node never sees PORT.

Two fixes:

• Run
export PORT=4000 first.
• Or run
PORT=4000 node server.js to set it for that one command only.

"Node only reads environment variables from a
.env file" is wrong. Node reads the real environment. It reads .env files only when you ask it to, for example with --env-file.