There are two ways to configure environment variables in Node.js: use the process.env object and set environment variables by assigning property values. Using the dotenv library, environment variables in the .env file are imported and accessed through process.env.
How to configure environment variables in Node.js
There are two ways to configure environment variables in Node.js Main methods:
1. Use the process.env object
process.env
is a global object that contains the environment variables of the current process . To set environment variables, you assign them to properties of process.env
:
<code>process.env.MY_VARIABLE = "my_value";</code>
2. Using the dotenv library
dotenv
is a Node.js library that can automatically load environment variables, which are stored in the .env
file. To use dotenv
:
npm install dotenv
in the project root directory. env
file and add the following content: <code>MY_VARIABLE=my_value</code>
dotenv
and load .env
File: <code>require('dotenv').config();</code>
Now you can access environment variables via:
<code>console.log(process.env.MY_VARIABLE); // 输出 "my_value"</code>
Note:
.env
files to manage environment variables in different environments (e.g. development, production). process.env
object, be sure to set the environment variables before the script is closed, otherwise they will be lost. dotenv
library, make sure to load the .env
file before using environment variables. The above is the detailed content of How to configure environment variables in nodejs. For more information, please follow other related articles on the PHP Chinese website!