ExpressJS项目运行出现MODULE_NOT_FOUND错误:无法加载../config/db.config.js模块求助
Hey there, let's work through this module not found error step by step—this is a super common issue with relative paths in Node.js, so we'll get it sorted quickly!
First, let's break down the core problem: your db.js file is trying to import ../config/db.config.js, but Node can't locate that file. From your error message, we know db.js lives directly in your project root (/Users/umairkhan/Documents/nodejs/bohra-calendar/db.js). The ../ in the path tells Node to look one directory up from db.js—which would take it outside your project folder entirely (to /Users/umairkhan/Documents/nodejs/), where there's no config folder. That's why the original path was wrong!
Even when you tried ./config/db.config.js and still got an error, here are the key things to check:
1. Verify Your Project Directory Structure
Double-check that your project root (bohra-calendar) has the exact structure below. If the config folder or db.config.js file is missing/misplaced, the import will fail:
bohra-calendar/ ├── db.js ├── config/ │ └── db.config.js ├── models/ │ └── event.model.js ├── controllers/ │ └── event.controller.js ├── routes/ │ └── event.routes.js └── server.js
2. Check for Filename/Directory Spelling & Case Sensitivity
Node.js (especially on macOS/Linux) is case-sensitive when it comes to file paths. Make sure:
- The folder is named
config(notConfigorCONFIG) - The file is named
db.config.js(notDB.config.js,db.Config.js, or a typo likedb.configs.js)
3. Test with Absolute Paths to Eliminate Ambiguity
If relative paths are still causing issues, use Node's __dirname (which gives the absolute path of the current file) to build a foolproof import path. Update your db.js code like this:
const mysql = require("mysql"); const path = require('path'); // Add this line to use the path module // Use __dirname to reference the current file's directory, then point to config var dbConfig = require(path.join(__dirname, './config/db.config.js')); // Rest of your connection code stays the same... const connection = mysql.createConnection({ host: dbConfig.HOST, user: dbConfig.USER, password: dbConfig.PASSWORD, database: dbConfig.DB }); connection.connect(error => { if (error) throw error; console.log("Successfully connected to the database."); }); module.exports = connection;
4. Clear Node Module Cache (Just in Case)
Sometimes Node caches module paths, which can cause stale errors. Try restarting your terminal and running your server again, or use this command to bypass cache temporarily:
node --no-cache server.js
If none of these steps work, double-check that db.config.js actually exists in the correct location—sometimes we forget to create the file, or it got saved in the wrong folder by accident!
内容的提问来源于stack exchange,提问作者Umair Khan Jadoon

