Mian Saqlain
Mian Saqlain

Reputation: 33

setting environment variable for changing the port dynamically in express node.js

I have an index.js app running on my server that works on port 3000 and I'm changing it by environment variable but it's still not working. I am trying to follow a tutorial and it says.

 1- Create an environment variable for port or run default 3000 port.
 2- Pass that variable to to app.listen()
 3- Set port=5000

But port isn't changing and remains still 3000. It can't setting the port to 5000.

The code of index.js is here:

//index.js
const express = require('express');
var app = express();
app.get('/', (req, res)=>{
    res.send('Hello World!!!');
});
const port = process.env.PORT || 3000 ; 
app.listen(port, () => console.log('listening on port ' + port));

The output in terminal is given below:

//terminal
PS F:\node practical\Restful APIs\express-demo> set PORT=5000
PS F:\node practical\Restful APIs\express-demo> nodemon index.js
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node index.js`
listening on port 3000[enter image description here][1]

Upvotes: 1

Views: 5505

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17868

You can use dotenv package to set port dynamically from environment file.

After installing it (npm i dotenv), you use it like this in the first lines if your main file (index.js or app.js)

require("dotenv").config();

Then you will need to create an .env file in the main folder of app, with this content:

PORT=5000

And your process.env.PORT will be 5000.

Upvotes: 1

Related Questions