Last modified: Jun 24, 2025 By Alexander Williams
Fix Node.js Error: Cannot find module
Node.js developers often encounter the "Cannot find module" error. This error occurs when Node.js fails to locate a required module. Understanding and fixing it is essential.
Table Of Contents
What Causes the Error?
The error happens when Node.js cannot find the module you tried to import. Common causes include missing dependencies, incorrect paths, or installation issues.
For example, if you run:
const express = require('express');
You might see:
Error: Cannot find module 'express'
Common Solutions
1. Install Missing Dependencies
Most often, the module is missing. Use npm install to add it.
npm install express
2. Check Module Paths
Ensure the path in require()
is correct. For local files, use relative paths like ./module
.
const myModule = require('./my-module');
3. Verify Node_modules
Node.js looks for modules in the node_modules folder. Ensure it exists and contains the required module.
Advanced Troubleshooting
Clear npm Cache
A corrupted cache can cause issues. Clear it with:
npm cache clean --force
Reinstall Dependencies
Delete node_modules and package-lock.json, then run:
npm install
Check Node.js Version
Some modules require specific Node.js versions. Verify compatibility.
Best Practices
To avoid this error:
- Always run
npm install
after cloning a project. - Double-check paths in
require()
. - Keep dependencies updated.
Conclusion
The "Cannot find module" error is common but fixable. Most cases resolve by installing dependencies or correcting paths. Follow best practices to minimize occurrences.