1

I am trying to set and get environment variable in node js .I tried like this I create the test.js file And add this line

console.log(process.env.NODE_ENV);

Run like this

 set NODE_ENV=production&&node test.js

It gives me undefined

user944513
  • 12,247
  • 49
  • 168
  • 318

3 Answers3

5

NODE_ENV=production node test.js on linux and $env:NODE_ENV = 'production'; node test.js in powershell.

Vladyslav Usenko
  • 2,296
  • 8
  • 18
1

In addition to the accepted answer:

From nodejs docs

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process.

So you can also do something like:

process.env.foo = 'bar';
console.log(process.env.foo);

Assigning a property on process.env will implicitly convert the value to a string.

process.env.test = null;
console.log(process.env.test);
// => 'null'

Note: There are some env variables which you can set only before any codes are executed.

Also note:

On Windows operating systems, environment variables are case-insensitive.

process.env.TEST = 1;
console.log(process.env.test);
// => 1
1565986223
  • 6,420
  • 2
  • 20
  • 33
0
1. create a package.json file.
2. install the dotenv npm package

make a .env file in your root directory. 
//env 
NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************

Now if you want to call your port in any file or server.js it will be like this.

const port = process.env.PORT;
console.log(`Your port is ${port}`);
Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26