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

5
  • u can read this article medium.com/the-node-js-collection/… hope it will help Commented Apr 23, 2019 at 7:49
  • Try NODE_ENV=production node test.js Commented Apr 23, 2019 at 7:49
  • 2
    set creates shell variables, not environment variables. Commented Apr 23, 2019 at 7:51
  • You can read this answer stackoverflow.com/a/57509175/11127383 Commented Aug 15, 2019 at 11:48
  • You have to do EXPORT NODE_ENV instead of SET NODE_ENV Commented Oct 4, 2020 at 3:18

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.