简体   繁体   English

如何在 nodejs 中持久化环境变量?

[英]how can i persist environment variables in nodejs?

I am in production environment on a vps that has linux.我在具有 linux 的 vps 上的生产环境中。 I have a file where I try to set my environment variables.我有一个文件,我尝试在其中设置环境变量。 my variables are in a file called environment.js .我的变量在一个名为environment.js的文件中。

the content of my file is like this:我的文件内容是这样的:

process.env.NODE_ENV = "prod";
console.log(process.env.NODE_ENV);
process.env.SEED = "seed";
console.log(process.env.SEED);
process.env.SEED_PORTAL = "seed_bee"
console.log(process.env.SEED_PORTAL);
process.env.HOST = "http://3.86.232.97";

then I run然后我跑

node environment.js

and I would expect the values to persist, but these variables are not global, they appear as undefined where I try to use them in other projects where I use nodejs我希望这些值保持不变,但这些变量不是全局的,它们在我尝试在我使用 nodejs 的其他项目中使用它们时显示为未定义

why?为什么?

When you set environment variables manually in node they only persist to that instance of node, since you're setting them in memory and not on the disk.当您在节点中手动设置环境变量时,它们仅保留到该节点实例,因为您将它们设置在 memory 而不是磁盘上。 If you're looking to share them across processes, one way is to use dotenv as Iggnaxios pointed out, in all of the applications, and have the same variables in each application's .env file, or have them all use the same .env file.如果您希望跨进程共享它们,一种方法是在所有应用程序中使用Iggnaxios指出的 dotenv,并在每个应用程序的.env文件中使用相同的变量,或者让它们都使用相同的.env文件.

Node will also pull environment variables from your operating system. Node 还将从您的操作系统中提取环境变量。 See How to permanently export a variable in Linux?请参阅如何永久导出 Linux 中的变量? on how to set environment variables in Linux关于如何在 Linux 中设置环境变量

to work with environment variables you must install the dotenv library要使用环境变量,您必须安装dotenv

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

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