Read environment variables in Node.js

1.6k2011 年提問 · Jayesh ·javascriptnode.jsenvironment-variables 主題:Node 與工具鏈 → 在 Stack Overflow 看原文 ↗

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

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

重點答案

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