14

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?

2
  • Both process and globals are globally accessible variables in node. Attaching thing to either just means that thing is attached to different objects. Can you clarify your question a little? What exactly are you asking?
    – zero298
    Commented Oct 17, 2018 at 19:10
  • As you say one is an environment variable and the other is set by your program. With process.env you can read the variables set in the system's environmnet. For example... THING=42 node server.js
    – F.bernal
    Commented Oct 17, 2018 at 19:10

4 Answers 4

10

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.

4

The choice in my opinion must be something like this. 1)If the variable depends on the environment it must be set in process.env 2)If the variable is just a constant that is accessible from the entire application it must be set to global.

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

1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.