0

I need to set environment variable for my NodeJS application. I'm using OS W10. I tried wrote in CMD

SET PORT=5000

When i wrote SET in CMD i saw value PORT=5000, but if i closed CMD and opend it one again and wrote again SET PORT i got message: Environment variable port not defined.

And if i try to get data from Node.JS application via command process.env.PORT i got value undefined. Do you have anybody experience with this isssue ?

Thanks.

Tom
  • 77
  • 7
  • Does this answer your question? [Setting Environment Variables for Node to retrieve](https://stackoverflow.com/questions/22312671/setting-environment-variables-for-node-to-retrieve) – Klaycon Nov 12 '19 at 20:57
  • I think it is not my case. He needs to load env settings, but i have problem with their settings. If i write in Node.JS code process.env i see a lot of values, but my set PORT=5000 value is not there. – Tom Nov 12 '19 at 21:08

2 Answers2

1

An environment variable set in a Windows 10 command shell persists only for the lifetime of that command shell and is only seen in that command shell (or in child processes).

So, if you want to set an environment variable in the command shell for your node.js app, you have to set it in that very command shell that you're about to run your node.js app from. This can either be done manually or you can create a batch file that sets the environment variable and then runs your node.js program.

If you want to set a persistent environment variable that is automatically available in all future command shells, then you can go into Windows settings and modify the default environment that is passed to all new command shells. Here are some steps to do that:

  1. Open Windows Settings
  2. Type environment in the search box in the settings window.
  3. If you are logged in as an administrator, you should get a drop-down that contains two options, edit system environment variables or edit environment variables for your account. Pick the desired choice.
  4. A dialog comes up where you can then edit, add or delete persistent environment variables.

enter image description here

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

SET only sets the environment setting for current session, once closed you loose it. In order to get PORT value using process.env.PORT, you need to set PORT first then run your server within same CMD window.

If you are using BASH (Git Bash) you can do it using one line

PORT=5000 node server.js

I highly recommend using DOTENV package to manage your Environment Variables.

Shivam
  • 3,514
  • 2
  • 13
  • 27