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
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
Share Improve this question asked Apr 23, 2019 at 7:47 user944513user944513 12.8k52 gold badges185 silver badges348 bronze badges 5- u can read this article medium./the-node-js-collection/… hope it will help – sayalok Commented Apr 23, 2019 at 7:49
-
Try
NODE_ENV=production node test.js
– Héctor Valls Commented Apr 23, 2019 at 7:49 -
2
set
creates shell variables, not environment variables. – Alnitak Commented Apr 23, 2019 at 7:51 - You can read this answer stackoverflow./a/57509175/11127383 – Daniel Danielecki Commented Aug 15, 2019 at 11:48
- You have to do EXPORT NODE_ENV instead of SET NODE_ENV – kta Commented Oct 4, 2020 at 3:18
3 Answers
Reset to default 5NODE_ENV=production node test.js
on linux and $env:NODE_ENV = 'production'; node test.js
in powershell.
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
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}`);