如何解决运行 Node.js 应用程序时出现“找不到模块”错误?

问题描述 投票:0回答:1

我在尝试使用

npm start
命令运行 Node.js 应用程序时遇到问题。应用程序似乎无法找到入口点文件,导致“找不到模块”错误。

这是我收到的错误消息:

> PS C:\Users\rodri\NODE_CRUD> npm start dev
>
> > [email protected] start
> > nodemon app.js
>
> [nodemon] 2.0.19
> [nodemon] to restart at any time, enter `rs`
> [nodemon] watching path(s): *.*
> [nodemon] watching extensions: js,mjs,json
> [nodemon] starting `node app.js dev index.js`
> node:internal/modules/cjs/loader:936
>   throw err;
>   ^
>
> Error: Cannot find module 'C:\Users\rodri\NODE_CRUD\index.js'
>     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
>     at Function.Module._load (node:internal/modules/cjs/loader:778:27)
>     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
>     at node:internal/main/run_main_module:17:47 {
>          code: 'MODULE_NOT_FOUND',
>          requireStack: []
> }
> [nodemon] app crashed - waiting for file changes before starting...

根据错误消息,Node 正在尝试在

index.js
目录中查找
C:\Users\rodri\NODE_CRUD
文件,但该文件似乎不存在。

这是我的项目结构:

node_crud_api/
├── config/
│   └── app.config.js
├── middleware/
│   └── errors.js
├── routes/
│   └── app.routes.js
├── app.js
├── package.json
└── index.js

这是我的

package.json
index.js
文件中的相关代码:

package.json

{
  "name": "node_crud_api",
  "version": "1.0.0",
  "description": "to make apps back end",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  // ...
}

index.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const { MONGO_DB_CONFIG } = require("./config/app.config");
const errors = require("./middleware/errors");

// ...

app.listen(process.env.port || 4000, function () {
  console.log("Ready to go!");
});

我已仔细检查项目根目录中是否存在

index.js
文件,但我仍然遇到此问题。 有人可以帮助我了解可能导致此“找不到模块”错误的原因以及如何解决它吗?

javascript node.js npm nodemon modulenotfounderror
1个回答
0
投票

参考此代码。

{
  "name": "node_crud_api",
  "version": "1.0.0",
  "description": "to make apps back end",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js" // Use "index.js" instead of "app.js"
  },
  // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.