Home > Net >  port undefined run by npm run start
port undefined run by npm run start

Time:03-02

I write following code in nodeJS :

const port = process.env.port;
const app = express();
const routes = require('./routes/routes');
app.use('/', routes);
app.listen(port, console.log('your browser run on port '   port));

when i run code by nodemon(npm run start), port variable is undefined while when i run it with node(node app.js), the port variable contains the value of the port where the program is running. Why the program run by nodemon the value of the port variable is undefined?

CodePudding user response:

Export the port beforehand.

export port=8080

Additionally, use some fallback.

const port = process.env.port || "3000"

Also note, by convention, environment variables are upper cases.

export APP_PORT=8080
const port = process.env.APP_PORT || "3000"

CodePudding user response:

If you don't have .env file create one. Write the port value in

port=8080

install the dotenv from npm

npm install dotenv

add the this line before define port variable

require('dotenv').config()
  • Related