我正在尝试在我的 Node 服务器上使用 dotenv 实现环境变量,但是我无法从位于根目录中的 .env 文件加载它们。当我运行 const dotenv = require("dotenv").config({debug: true});
我遇到以下消息:"USER" is already defined in process.env and will not be overwritten
此外,当我尝试加载页面时,遇到以下错误:ER_DBACCESS_DENIED_ERROR: Access denied for user ''@'localhost' to database '_api'
.env:
USER=root
PASS=
最佳答案
来自 Variables overwriting/priority .
Environment variables that are already set will not be overwritten, that means that the command line variables have a higher priority over all those defined in env files;
还有这个What happens to environment variables that were already set?
We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.
如果你想覆盖 process.env 你可以这样做:
const fs = require('fs')
const dotenv = require('dotenv')
const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
for (const k in envConfig) {
process.env[k] = envConfig[k]
}
关于javascript - Dotenv 无法覆盖键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65407397/