Languages
[Edit]
EN

Node.js - common way to pass environment variables to Node.js process (Windows, Linux, macOS, etc.)

6 points
Created by:
Dexter
660

In this article, we would like to show you common way to pass environment variables to Node.js process using any command line.

Quick solution (run in any command line):

Where:

  • cross-env is cross platform tool that passes environment variable to indicated process,
  • VARIABLE_NAME is environment variable name that we want to pass,
  • VARIABLE_VALUE is environment variable value that we want to pass,
  • script.js is file name that will be executed receiving the environment variable.

 

Note: to install cross-env tool use npm install cross-env command (locall installation).

Hint: we can use spaces and special characters in variable value by using npx cross-env VARIABLE_NAME="VARIABLE NAME" node script.js construction.

 

Practical example

Edit

In this example, we pass ADMIN_USERNAME and ADMIN_PASSWORD environment variables into script.js script. Then we access passed variables inside script.js script using process.env property.

Project preparation

Edit

In your project directory you should do the following things:

1. Install dependencies using:

Note: cross-env package will be installed locally in your project directory.

2. Create script.js file:

 

Script executing

Edit

Run in any command line:

Script output:

 

See also

Edit
  1. Node.js - read .env file (custom solution)

  2. Bash - pass environment variables to Node.js process (during command running)

  3. cmd.exe - pass environment variables to Node.js process (during command running)

References

Edit
  1. Process | Node.js v19.1.0 Documentation

Alternative titles

  1. Node.js - platform independent way to pass environment variables to Node.js process (during command running)
  2. Node.js - universal way to pass environment variables to Node.js process (during command running)
  3. Node.js - common way to pass env variables to Node.js process (during command running)
  4. Node.js - platform independent way to pass env variables to Node.js process (during command running)
  5. Node.js - universal way to pass env variables to Node.js process (during command running)
  6. Node.js - common way to pass environment variables to Node.js process (during command running)
  7. Node.js - cross platform to pass environment variables to Node.js process (Windows, Linux, macOS, etc.)
  8. Node.js - cross platform to pass env variables to Node.js process (Windows, Linux, macOS, etc.)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join