How to configure environment variables in nodejs

下次还敢
Release: 2024-04-21 03:46:54
Original
925 people have browsed it

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 nodejs

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>
Copy after login

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:

  • Install the library: npm install dotenv
  • Create a file named in the project root directory. env file and add the following content:
<code>MY_VARIABLE=my_value</code>
Copy after login
  • In your Node.js script, import dotenv and load .env File:
<code>require('dotenv').config();</code>
Copy after login

Now you can access environment variables via:

<code>console.log(process.env.MY_VARIABLE); // 输出 "my_value"</code>
Copy after login

Note:

  • Always Use uppercase letters to define environment variable names to avoid conflicts with other variables.
  • It is a good idea to use different .env files to manage environment variables in different environments (e.g. development, production).
  • When using the process.env object, be sure to set the environment variables before the script is closed, otherwise they will be lost.
  • When using the 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!