user14339485
user14339485

Reputation:

Could not access windows environment variable in Node

Today I was trying to write an environment variable like this:

set PORT=5000

But when I access it through the process.env.PORT variable in node, it gives undefined.

I might be missing something or my PC is malfunctioning, so any help would be appreciated, Thanks

Upvotes: 0

Views: 2357

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8783

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

Upvotes: 1

Related Questions