简体   繁体   English

节点 js,process.env 不读取环境变量

[英]Node js, process.env not reading enviroment variables

Even though I can see that an environment variable was created on windows, process.env always returns undefined .尽管我可以看到在 windows 上创建了一个环境变量,但process.env总是返回undefined I did set all my variables, and when I check them manually, they all appear in the prompt, but the process.env always stays undefined.我确实设置了所有变量,当我手动检查它们时,它们都出现在提示中,但process.env始终保持未定义。

PS I don't have admin privileges, except when I check the process.env.NODE_ENV . PS我没有管理员权限,除非我检查process.env.NODE_ENV

在此处输入图像描述

You need to read them first.你需要先阅读它们。

Use the dotenv package.使用dotenv package。

Install:安装:

npm install dotenv

In you project code:在您的项目代码中:

require('dotenv').config()

Add.env file in you project folder like this:在您的项目文件夹中添加.env 文件,如下所示:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

Try get env var like this:尝试像这样获取环境变量:

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

By the way, it is not enough to write them to a file in order for them to become environment variables.顺便说一句,将它们写入文件以使其成为环境变量是不够的。 You need to write them in the console and then they become environment variables.您需要在控制台中编写它们,然后它们成为环境变量。 The.env file method lets you write them to a file and read them from there through the donenv package. .env 文件方法允许您将它们写入文件并通过 donenv package 从那里读取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM