How to Set up and read a .env file in node.js?

本文详细介绍了如何在Node.js项目中使用.env文件管理环境变量,包括添加变量、忽略git提交、安装dotenv包并配置入口文件。通过设置不同的端口,展示如何根据开发或生产状态动态选择端口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In five easy steps, we’ll update.gitignore, create a.env file, and read it:

  1. Add .env to gitignore
# dotenv environment variables file
.env
.env.test
  1. Install npm package dotenv
npm i dotenv
  1. It’s time to use our env variables.
    Add some variable to your .env file, for exemple we’re going to add a status for our nodejs app and define two different ports, one for development status and one for production
STATUS =production
DEV_PORT =7000
PROD_PORT = 8000
  1. add this in the beginning of your index.js file to load .env file
require("dotenv").config();
  1. Then in our entry point we’re testing if the STATUS is production we’re going to use the PROD_PORT else we’re using the DEV_PORT
    port
  2. Run the application Change the status variable in your .env and see what happens
    node
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值