How to resolve "Cannot find module" error in Node

Updated onbyAlan Morel
How to resolve "Cannot find module" error in Node

When you are working in Node, you will sometimes encounter the error Cannot find module 'module-name' with the error code MODULE_NOT_FOUND.

The error looks like this:

BASH
internal/modules/cjs/loader.js:796 throw err; ^ Error: Cannot find module 'module' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17) at Function.Module._load (internal/modules/cjs/loader.js:686:27) at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10) at internal/main/run_main_module.js:17:11 { code: 'MODULE_NOT_FOUND', requireStack: [] }

In this post, we'll learn how to resolve this error.

What is the problem?

The issue is that Node is unable to find the module that you are trying to import into your Node application.

The most common reason for this is that you simply haven't installed the project's dependencies yet.

The project's dependencies are listed in the package.json file at the root of the project.

The Solution

To fix the Cannot find module error, simply install the missing modules using npm.

To so, you can use the following command:

BASH
npm install

If you are using the yarn package manager, you can use the following command:

BASH
yarn install

This will install the project's dependencies into your project so that you can use them.

Sometimes, this might still not resolve it for you. In this case, you'll want to just delete your node_modules folder and lock file (package-lock.json or yarn.lock) and try again.

This is how you can delete the node_modules folder and lock files:

BASH
rm -rf node_modules rm package-lock.json rm yarn.lock

Local files

If your module is not coming from a remote source, you are seeing the error because the path to the local file is not correct.

Try to confirm that the path pointing to the local module is correct and your error should be resolved.

Conclusion

The Cannot find module error is a common error that usually happens when dependencies are not installed. Once you install your dependencies and ensure that the paths are correct, you can resolve the error and run your application successfully.

Hopefully, this resolved the issue for you.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.