javascript - 对子目录中的 .js 文件使用 require() 时出现 MODULE_NOT_FOUND 错误
问题描述
使用 ExpressJS,当我使用“node server.js”命令运行我的项目时,我收到以下错误:
node:internal/modules/cjs/loader:936 抛出错误;^
错误:找不到模块 '../config/db.config.js' 需要堆栈:
- /Users/umairkhan/Documents/nodejs/bohra-calendar/db.js
- /Users/umairkhan/Documents/nodejs/bohra-calendar/models/event.model.js
- /Users/umairkhan/Documents/nodejs/bohra-calendar/controllers/event.controller.js
- /Users/umairkhan/Documents/nodejs/bohra-calendar/routes/event.routes.js
- /Users/umairkhan/Documents/nodejs/bohra-calendar/server.js 在 Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) 在 Function.Module._load (node:internal/modules/ cjs/loader:778:27) 在 Module.require (node:internal/modules/cjs/loader:1005:19) 在 require (node:internal/modules/cjs/helpers:94:18) 在 Object. (/Users/umairkhan/Documents/nodejs/bohra-calendar/db.js:2:16) 在 Module._compile (node:internal/modules/cjs/loader:1101:14) 在 Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) 在 Module.load (node:internal/modules/cjs/loader:981:32) 在 Function.Module._load (node:internal/modules/cjs/loader :822:12) 在 Module.require (node:internal/modules/cjs/loader:1005:19) { code: 'MODULE_NOT_FOUND', requireStack: [ '/Users/umairkhan/Documents/nodejs/bohra-calendar/db. ','
这是我在 db.js 文件中的代码:
const mysql = require("mysql");
var dbConfig = require("../config/db.config.js");
// Create a connection to the database
const connection = mysql.createConnection({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB
});
// open the MySQL connection
connection.connect(error => {
if (error) throw error;
console.log("Successfully connected to the database.");
});
module.exports = connection;
这是项目的目录结构。
我也试过这条路径:'./config/db.config.js' 但我仍然得到同样的错误。
有人可以帮忙吗?
解决方案
推荐阅读
- sql-server - SQL Server 2019,使用 T-SQL,我正在尝试从订单表中的订单号列中提取“-”和“/”之间的数据值
- java - Java Spring Boot 单元测试服务状态不为每个单元测试刷新
- python - 如何将子词典移动到另一个词典?
- java - Hibernate INSERT 未出现在数据库“JDBC 事务标记为仅回滚”中
- azure-devops - 能否以编程方式为 Azure DevOps 发布管道中的变量设置可覆盖的默认值?
- javascript - 我正在构建一个动态生成选项卡的组件,无法弄清楚如何传入标题以动态命名这些选项卡
- python - 对于每个 String S,打印 的偶数索引字符,后跟一个空格,然后是 的奇数索引字符
- python - 在 Python 中,如何将单词与列表相关联,然后从列表中随机打印一个值?
- sql - 如何添加一行以检查它是否存在?
- python - 条形图 df.plot() vs ax.bar() 结构 matplotlib