Last modified: Jun 30, 2025 By Alexander Williams
Fix Error: Cannot Find Module in Node.js
Node.js developers often face the "Error: Cannot find module" when using relative import paths. This error occurs when Node.js cannot locate the required file or module. Let's explore how to fix it.
Table Of Contents
Understanding the Error
The error appears when you try to import a module using a relative path, but Node.js fails to find it. Common causes include incorrect paths, missing files, or module installation issues.
// Example error when importing './app.js'
const app = require('./app'); // Error: Cannot find module './app'
Common Causes and Fixes
1. Incorrect File Path
Double-check your import path. Ensure the file exists in the specified location. Use absolute paths if needed.
// Wrong path (file doesn't exist)
const config = require('../config'); // Error
// Correct path (file exists)
const config = require('./config'); // Works
2. Missing File Extension
Node.js may need explicit file extensions. Try adding .js or .json to your import statement.
// Without extension (may fail)
const routes = require('./routes/index');
// With extension (more reliable)
const routes = require('./routes/index.js');
3. Case Sensitivity Issues
File systems are case-sensitive. Ensure your import matches the exact filename casing.
// Wrong case (may fail on Linux/macOS)
const someFile = require('../../someFile');
// Correct case
const someFile = require('../../SomeFile');
Advanced Solutions
Using path.resolve()
The path.resolve()
method helps create absolute paths, reducing relative path issues.
const path = require('path');
const app = require(path.resolve(__dirname, 'app.js'));
Checking Node Modules
For third-party modules like pg or mysql2, ensure they're installed. Run npm install module-name
.
# Install missing module
npm install socket.io-client
Debugging Tips
Use console.log(__dirname)
to check the current directory. Verify file existence with fs.existsSync()
.
const fs = require('fs');
console.log('File exists:', fs.existsSync('./app.js'));
Conclusion
The "Cannot find module" error is common but fixable. Check paths, extensions, and casing. Use absolute paths when needed. For third-party modules like puppeteer or ts-jest, ensure proper installation.
For specific cases, see our guides on fixing app.js errors or config file issues.