首页 > 解决方案 > 对子目录中的 .js 文件使用 require() 时出现 MODULE_NOT_FOUND 错误

问题描述

使用 ExpressJS,当我使用“node server.js”命令运行我的项目时,我收到以下错误:

node:internal/modules/cjs/loader:936 抛出错误;^

错误:找不到模块 '../config/db.config.js' 需要堆栈:

这是我在 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' 但我仍然得到同样的错误。

有人可以帮忙吗?

标签: javascriptnode.js

解决方案


推荐阅读