use the below command to set the port number in node process while running node JS program. And this port will only limited to this node process.
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
I recommend you using .environment file to keep your configuration separate.
Steps to follow:
- create a package.json file
- install the dotenv npm package
- write the code to read the .env
- run the code
.env
# .env.example
NODE_ENV=development
PORT=8626
# Set your database connection information here
API_KEY=your-core-api-key-goes-here
server.js file:
// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined
const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626
for more details you can check this: https://www.twilio.com/blog/working-with-environment-variables-in-node-js-html