Veronica
Veronica

Reputation: 5

How can I change the value of process.env.PORT in node.js? (Solved)

I've tried set PORT=5000 with no success and PORT=5000 node index.js which throws the following error: "The term 'PORT=4444' is not recognized as the name of a cmdlet, function, script file, or operable program."

I saw the same question resolved for Ubuntu, but I'm using Windows 10 (and VS Code console).

Thanks in advance!

Edit: I found that running $env:PORT=4444 in VS Code terminal works, no need to install additional modules in this case.

Upvotes: 0

Views: 1625

Answers (2)

Samim Hakimi
Samim Hakimi

Reputation: 725

Try this way:

1:

Install dotenv package:

npm i dotenv

2:

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of PORT=444. For example:

// If you want to change the PORT number just changed it from here.

PORT=4444

3:

require('dotenv').config()

By requiring this you are setting the PORT number from Process.env.PORT that you have recently assigned.

Or:

if you want to set your port number without using .env try this way:

In your index.js just set the port number for instance: const port = 4444;

Upvotes: 1

Daniel
Daniel

Reputation: 357

Common sense for this kind of configuration is to use .env-Files to configure your environments.

  1. For this to work you would need the dotenv-Module.

  2. Create a File named .env in your app's root-folder and add your desired configuration like this:

PORT=5000
  1. In your app you will have to call this at a very early stage.
require('dotenv').config()
  1. You can then access your environment-variables in your code like this:
app.listen(process.env.PORT || '3000')

Upvotes: 0

Related Questions