To read environment variables in Node.js, you can use the process.env
object.
The process.env
object contains a property for each of the environment variables that are available to the Node.js process. You can access the value of an environment variable using dot notation or bracket notation.
Here’s an example of how you can read an environment variable in Node.js:
const port = process.env.PORT || 3000;
console.log(port); // the value of the PORT environment variable, or 3000 if it is not set
In this example, the port
variable is assigned the value of the PORT
environment variable, or 3000
if the PORT
variable is not set.
You can also use the process.env
object to set environment variables for the Node.js process. For example:
process.env.NODE_ENV = 'production';
This will set the NODE_ENV
environment variable to 'production'
.
Keep in mind that environment variables are typically set outside of the Node.js process, such as in a shell script or in the operating system’s environment variables.