user944513
user944513

Reputation: 12729

how to set and get environment variable in node js?

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

Upvotes: 1

Views: 6280

Answers (3)

1565986223
1565986223

Reputation: 6718

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

Upvotes: 1

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

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

Upvotes: 0

Vladyslav Usenko
Vladyslav Usenko

Reputation: 2376

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

Upvotes: 5

Related Questions