Node.js新手求助:运行项目时出现Cannot find module './.env'错误
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:
- You don't actually have a
.envfile in the directory you're trying to load it from, or - You're trying to load it the wrong way (using
requireinstead 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 -ain your project root directory. Look for.envin the list. - On Windows: Run
dir /ain Command Prompt (or useGet-ChildItem -Forcein 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:
- Install the package:
npm install dotenv --save - At the very top of your
server.jsfile (before any other code that uses environment variables), add this line:require('dotenv').config(); - Now you can access your
.envvariables usingprocess.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.jsis in a subdirectory (likesrc/server.js), you might need to specify the path to your.envfile explicitly:require('dotenv').config({ path: '../.env' }); - Make sure
.envis added to your.gitignorefile so you don't accidentally commit sensitive credentials (like API keys or database passwords) to version control.
内容的提问来源于stack exchange,提问作者luis dmz

