Read environment variables in Node.js

2018-12-31 12:51发布

Is there a way to read environment variables in Node.js code?

Like for example Python's os.environ['HOME'].

5条回答
人间绝色
2楼-- · 2018-12-31 13:00

If you want to use a string key generated in your Node.js program, say, var v = 'HOME', you can use process.env[v].

Otherwise, process.env.VARNAME has to be hardcoded in your program.

查看更多
高级女魔头
3楼-- · 2018-12-31 13:01
process.env.ENV_VARIABLE

Where ENV_VARIABLE is the name of the variable you wish to access.

See Node.js docs for process.env.

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 13:12

You can use env package to manage your environment variables per project:

  • Create a .env file under the project directory and put all of your variables there.
  • Add this line in the top of your application entry file:
    require('dotenv').config();

Done. Now you can access your environment variables with process.env.ENV_NAME.

查看更多
孤独寂梦人
5楼-- · 2018-12-31 13:19

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });
查看更多
何处买醉
6楼-- · 2018-12-31 13:24

When using Node.js, you can retrieve environment variables by key from the process.env object:

for example

var mode   = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'

Here is the answer that will explain setting environment variables in node.js

查看更多
登录 后发表回答