How to read environment variables setting from Node.js?
I have a small project with Node.js. I wrote some code as below and I want to it only execute if the current environment is the production
mode.
var fs = require('fs');
if(check environment is production mode){ // I want to check environment here
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
}
My Nodejs version is v12.18.3
Thanks for any suggestions.
-
S1
SURASITH KAEWVIKKIT Jul 07 2021
The
process
core module of Node.js provides theenv
property that hosts all the environment variables that were set at the moment the process was started.process.env.NODE_ENV
NODE_ENV
is an environment variable and it's set to default todevelopment
You can set the value to other mode (value)
-
N0
Nguyen Truong Giang Jul 07 2021
You can do as below:
if (process.env.NODE_ENV == "production") { // Your code here }
I hope it works for you.
-
H0
Huỳnh Ngọc Thiện Jul 07 2021
The
process.env
property returns an object containing the user environment.For example, I create
NODE_EVN
with valueproduction
as below:$ node -e 'process.env.NODE_ENV = "production"'
And you can write log of that variable as below:
var mode = process.env.NODE_ENV; if (mode == "production") { // Your code here }
I hope it works for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.