简体   繁体   English

Node.js:process.env与全局有何不同?

[英]Node.js: How does process.env differ from global?

How is setting an environment variable like process.env.thing = 42 different from creating a global variable like global.thing = 42 ? 设置类似于process.env.thing = 42的环境变量与创建诸如global.thing = 42的全局变量global.thing = 42不同?

When would prefer process.env.thing over global ? 什么时候更喜欢process.env.thing不是global What are the pros/cons of both objects? 这两个对象的优缺点是什么?

If you start your node.js application you may want to use some different "environments", like API-URLs and stuff like this, because in a production / live environment those URLs are usually different in comparision to your local development environment. 如果启动node.js应用程序,则可能需要使用一些不同的“环境”,例如API-URL和类似的东西,因为在生产/现场环境中,这些URL与本地开发环境相比通常是不同的。

This means that you can inject those paths using a .env file for example BEFORE starting your application. 这意味着您可以在启动应用程序之前使用.env文件注入这些路径。

This is an example: 这是一个例子:

NODE_API_URL=https://myApi.com/myEndpoints myApp.js

The global.thing = bla line will be read after the environment variables were set. 设置环境变量 ,将读取global.thing = bla行。

Once the application is running the environment variables and the other global definitions can be accessed by the app. 一旦应用程序运行,该应用程序即可访问环境变量和其他全局定义。

global is the global object. global是全局对象。 process is available globally, because it is a property of global . process是全局可用的,因为它是global的属性。 In fact: 事实上:

global.process === process //-> true

process.env has properties set to the environment variables of the system. process.env属性设置为系统的环境变量。 These can be set a variety of ways outside of node itself, and read in by accessing properties of process.env . 可以在节点本身之外设置各种方式,并通过访问process.env属性来读取这些方式。

At the command line try: 在命令行中尝试:

FOO=bar node -e "process.env.FOO"

The process module is just a globally available thing. 处理模块只是全球可用的东西。

The choice in my opinion must be something like this. 我认为选择必须是这样的。 1)If the variable is depend on environment it must bet set in process.env 2)If the variable is just a constant that is accessible from entire application it must be set to global. 1)如果变量取决于环境,则必须在process.env中设置。2)如果变量只是可以从整个应用程序访问的常量,则必须将其设置为global。

I think if you don't face this 2 points you don't have need to store some value in both 我认为,如果您不面对这2点,则无需在这两个方面都存储一些值

from the docs NodeAPI 来自docs NodeAPI

The process object is a global that provides information about, and control over, the current Node.js process. 流程对象是一个全局对象,可提供有关当前Node.js流程的信息并对其进行控制。 As a global, it is always available to Node.js applications without using require(). 全局而言,它始终可用于Node.js应用程序,而无需使用require()。

You want to attach your environment variables to this object to make sure that there is no other pollution of globals. 您想要将环境变量附加到该对象,以确保不会对全局变量造成其他污染。

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

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