Skip to content

Improve "Cannot find module" error #26588

Closed
@tom-dalton-fanduel

Description

@tom-dalton-fanduel

Is your feature request related to a problem? Please describe.

While trying to debug an issue, I found the error message from node to be slightly misleading and/or not as useful as it could have been.

Here is a toy example of the issue:

We have a package called "foo". It consists of a package.json and dist/entry.js:

package.json:

/tmp/node_demo › cat node_modules/foo/package.json 
{
  "name": "foo",
  "version": "0.1.1",
  "main": "dist/entry.js"
}

dist/entry.js

/tmp/node_demo › cat node_modules/foo/dist/entry.js 
console.log("Loaded foo module")

We can import this package, everything is good:

/tmp/node_demo › node
> require("foo")
Loaded foo module
{}

The improvement comes when we delete the entrypoint for our foo module. In my real-world case, this was done by an overzealous package-trimming routing in a CI pipeline, but I guess there are probably other ways it can occur. It's clearly the user's 'fault', but the error message isn't super obvious:

/tmp/node_demo › rm node_modules/foo/dist/entry.js 
/tmp/node_demo › node
> require("foo")
Error: Cannot find module 'foo'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
> /tmp/node_demo › 

The issue here is that the error message Error: Cannot find module 'foo' isn't super helpful, because you have a look in node_modules, and you see a directory foo/, and you see that directory contains package.json. Maybe you also see it contains a src/ dir, a tests/ dir, and all sorts of other stuff. In my case, this led me to believe the error was that the node interpreter was somehow configured not to look in the local node_modules directory, and led to a fair bit of wild-goose chasing.

Describe the solution you'd like

It would be better if the error message directly referred to the missing [main/entry-point]file. E.g. if the error was something like:

Error: Cannot find load main file "dist/entry.js" when loading module 'foo'
    at Function....
    ...

it would be immediately obvious why node can't load the module.

Describe alternatives you've considered

The obvious alternative is to do nothing, which would maintain the current error messaging and behaviour.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions