简体   繁体   中英

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 ?

When would prefer process.env.thing over 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.

This means that you can inject those paths using a .env file for example BEFORE starting your application.

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.

Once the application is running the environment variables and the other global definitions can be accessed by the app.

global is the global object. process is available globally, because it is a property of global . In fact:

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

process.env has properties set to the environment variables of the system. These can be set a variety of ways outside of node itself, and read in by accessing properties of 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.

I think if you don't face this 2 points you don't have need to store some value in both

from the docs NodeAPI

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().

You want to attach your environment variables to this object to make sure that there is no other pollution of globals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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