0

I am learning environment variable in Nodejs. I followed a tutorial video and wrote the exact same code in VS Code to set PORT value in the terminal. But for some reason, the output of PORT is undefined.

In editor, my code is like

//This is index.js file
const port = process.env.PORT;
app.listen(port, () => {
    console.log(`listening to port ${port}...`)
})

In terminal, I typed set PORT=2000 and pressed Enter. In the next line of terminal, I typed node index.js. The output in the terminal is listening to port undefined.

My OS is Windows. I tried solutions online, such as PORT=2000 node index.js and SET PORT=2000 node index.js. But none of them worked.

Chloezhang
  • 39
  • 4
  • Which operating system are you using ? Is it windows if so your commands are perfect to set the env variables....If its mac/linux - export PORT=2000 – Ram Sankhavaram Dec 29 '20 at 10:18
  • I am using Windows OS. I don't understand why set PORT=2000 didn't work – Chloezhang Dec 29 '20 at 10:27
  • I have found an answer on stackflow this afternoon. It worked in my case. https://stackoverflow.com/questions/51945761/can-not-set-environment-variable-in-nodejs-app-windows – Chloezhang Dec 31 '20 at 07:43

1 Answers1

1

These are different ways you can set the environment variables in node in different operating systems:

# Windows CMD:
SET PORT=2000
# or
set PORT=2000

# OS X / Linux:
export PORT=2000

# Windows PowerShell:
$env:PORT=2000
SilverNak
  • 3,283
  • 4
  • 28
  • 44
Ram Sankhavaram
  • 1,218
  • 6
  • 11