javascript - Dotenv 无法覆盖键值对

标签 javascript node.js dotenv

我正在尝试在我的 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/

相关文章:

Javascript内存卡游戏最后一张牌不翻转

javascript - 创建包含文本内容的新 Google 云端硬盘文件 (javascript)

javascript - PostCSS:ExtractTextPlugin 运行两次

javascript - Javascript 模块模式和子模块初始化模式

linux - 陨石(mrt)命令什么都不做

node.js - Node js Express 中的持久 cookie

javascript - 如何检索 Meteor.js 集合然后在 DOM 加载后将其传递给函数

webpack - dotenv-webpack 在 webpack.config.js 中使用环境变量

javascript - Jest 不加载环境变量(即使使用 --setupFiles dotenv/config)

nuxt.js - 如何在 Nuxt 配置中设置 .env 文件路径?