How to read environment variables setting from Node.js?

Dung Do Tien Jul 07 2021 79

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.

Have 3 answer(s) found.
  • S

    SURASITH KAEWVIKKIT Jul 07 2021

    The process core module of Node.js provides the env 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 to development

    You can set the value to other mode (value) 

  • N

    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.

  • H

    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 value production 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.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close