简体   繁体   English

process.env变量的值与.env配置中的值不同

[英]process.env variables not the same value as in .env config

In a recent nodejs project, I had a very strange occurrence: I set the HOSTNAME variable in my .env file, and by the time it got included in the .js file, the HOSTNAME value was different from the one in .env. 在最近的nodejs项目中,发生了一个非常奇怪的事情:我在.env文件中设置了HOSTNAME变量,当它包含在.js文件中时,HOSTNAME值与.env中的值不同。 Why ? 为什么

-- -

Situation 情况

.env .env

HOSTNAME=foo.bar.com

server.js server.js

require('dotenv').config();
console.log("Hostname: ", process.env.HOSTNAME);

console output 控制台输出

Hostname: foo

Expected console output 预期的控制台输出

Hostname: foo.bar.com

-- -

Debugging 调试

  • Nodejs application is installed on a windows server 2008, where the machine's DNS entry is foo.bar.com. Nodejs应用程序安装在Windows Server 2008上,该计算机的DNS条目为foo.bar.com。 From the intranet, the machine is even reachable as " http://foo " (for whatever reason). 从Intranet,甚至可以通过“ http:// foo ”访问该计算机(无论出于何种原因)。
  • No other nodejs application runs on that server 该服务器上没有其他Node.js应用程序运行
  • Problem only occurs with HOSTNAME, no other variable name (at least not as far as I could find) 问题仅出现在HOSTNAME上,没有其他变量名(至少在我所能找到的范围内)
  • works perfectly fine if HOSTNAME=localhost and I run the application from the server browser 如果HOSTNAME = localhost,并且我从服务器浏览器运行该应用程序,则工作正常
  • works perfectly fine if I rename HOSTNAME to _HOSTNAME (and replace all occurrences of HOSTNAME in my code) 如果我将HOSTNAME重命名为_HOSTNAME(并且替换了我代码中所有出现的HOSTNAME),则可以正常工作
  • works perfectly fine if I run the code on my local machine and just have a .hosts entry "127.0.0.1 foo.bar.com" 如果我在本地计算机上运行代码并且只有一个.hosts条目“ 127.0.0.1 foo.bar.com”,则可以正常工作

I have fixed the issue by renaming to _HOSTNAME, but I would like to know WHY this happened, and if there are other .env variable names that might be affected by this strange occurrence 我已经通过重命名为_HOSTNAME来解决了该问题,但是我想知道为什么会这样,以及是否还有其他.env变量名可能会受到这种奇怪情况的影响

dotenv npm library skips the variables which already set in the host environment.You can find the more information about overriding existing system variables in official documentation. dotenv npm库会跳过已在主机环境中设置的变量。您可以在官方文档中找到有关覆盖现有系统变量的更多信息。

https://github.com/motdotla/dotenv#what-happens-to-environment-variables-that-were-already-set https://github.com/motdotla/dotenv#what-happens-to-environment-variables-that-已经设置

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

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