You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js新手求助:运行项目时出现Cannot find module './.env'错误

Fixing "Cannot find module './.env'" in Node.js

Hey there! Let's sort out that frustrating error you're seeing when trying to run your Node.js app. Here's what's going on and step-by-step fixes:

Why this happens

First off, Node.js doesn't natively recognize .env files as modules you can require() directly. That error is either telling you one of two things:

  1. You don't actually have a .env file in the directory you're trying to load it from, or
  2. You're trying to load it the wrong way (using require instead of a dedicated package).

Step 1: Check if your .env file exists

First, verify the file is there. Since .env is a hidden file, you'll need to show hidden files in your terminal:

  • On Mac/Linux: Run ls -a in your project root directory. Look for .env in the list.
  • On Windows: Run dir /a in Command Prompt (or use Get-ChildItem -Force in PowerShell).

If the file doesn't exist, create it in your project root with the format:

# Example .env content
PORT=3000
DATABASE_URL=mongodb://localhost/mydb
API_KEY=abc123

Step 2: Use dotenv to load your environment variables

Node.js can't parse .env files on its own—you need the dotenv package for that. Here's how to set it up:

  1. Install the package:
    npm install dotenv --save
    
  2. At the very top of your server.js file (before any other code that uses environment variables), add this line:
    require('dotenv').config();
    
  3. Now you can access your .env variables using process.env, like this:
    const port = process.env.PORT || 3000;
    app.listen(port, () => console.log(`Server running on port ${port}`));
    

Step 3: Clean up the incorrect require('./.env') line

Delete any line in your code that says require('./.env')—that's not how you load environment variables, and it will always throw an error even if the file exists (since Node.js tries to parse it as JavaScript, which it isn't).

Extra tips

  • If your server.js is in a subdirectory (like src/server.js), you might need to specify the path to your .env file explicitly:
    require('dotenv').config({ path: '../.env' });
    
  • Make sure .env is added to your .gitignore file so you don't accidentally commit sensitive credentials (like API keys or database passwords) to version control.

内容的提问来源于stack exchange,提问作者luis dmz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:43:24