javascriptnode.jsnpmnodemonmodulenotfounderror

How to resolve "Cannot find module" error when running Node.js app?


I'm encountering an issue when trying to run my Node.js application using the npm start command. The application seems to be failing to locate the entry point file, resulting in a "Cannot find module" error.

Here's the error message I'm receiving:

> PS C:\Users\rodri\NODE_CRUD> npm start dev
>
> > node_crud_api@1.0.0 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...

According to the error message, Node is trying to find the index.js file in the C:\Users\rodri\NODE_CRUD directory, but it doesn't seem to exist there.

Here's my project structure:

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

And here's the relevant code from my package.json and index.js files:

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!");
});

I've double-checked that the index.js file exists in the project's root directory, but I'm still encountering this issue. Can someone please help me understand what might be causing this "Cannot find module" error and how I can resolve it?


Solution

  • reference this code.

    {
      "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"
      },
      // ...
    }