Node.js - common way to pass environment variables to Node.js process (Windows, Linux, macOS, etc.)
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):
npx cross-env VARIABLE_NAME=VARIABLE_VALUE node script.js
Where:
cross-envis cross platform tool that passes environment variable to indicated process,VARIABLE_NAMEis environment variable name that we want to pass,VARIABLE_VALUEis environment variable value that we want to pass,script.jsis file name that will be executed receiving the environment variable.
Note: to install
cross-envtool usenpm install cross-envcommand (locall installation).
Hint: we can use spaces and special characters in variable value by using
npx cross-env VARIABLE_NAME="VARIABLE NAME" node script.jsconstruction.
Practical example
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
In your project directory you should do the following things:
1. Install dependencies using:
npm install cross-env
Note:
cross-envpackage will be installed locally in your project directory.
2. Create script.js file:
console.log('Admin username: ' + process.env.ADMIN_USERNAME);
console.log('Admin password: ' + process.env.ADMIN_PASSWORD);
Script executing
Run in any command line:
npx cross-env ADMIN_USERNAME=admin ADMIN_PASSWORD=admin node script.js
Script output:
Admin username: admin
Admin password: admin
See also
-
Bash - pass environment variables to Node.js process (during command running)
-
cmd.exe - pass environment variables to Node.js process (during command running)
References
Alternative titles
- Node.js - platform independent way to pass environment variables to Node.js process (during command running)
- Node.js - universal way to pass environment variables to Node.js process (during command running)
- Node.js - common way to pass env variables to Node.js process (during command running)
- Node.js - platform independent way to pass env variables to Node.js process (during command running)
- Node.js - universal way to pass env variables to Node.js process (during command running)
- Node.js - common way to pass environment variables to Node.js process (during command running)
- Node.js - cross platform to pass environment variables to Node.js process (Windows, Linux, macOS, etc.)
- Node.js - cross platform to pass env variables to Node.js process (Windows, Linux, macOS, etc.)