0
0
NodejsDebug / FixBeginner · 3 min read

How to Fix 'Cannot Find Module' Error in Node.js

The Cannot find module error in Node.js happens when the module path is wrong or the module is not installed. Fix it by checking the module name, installing missing packages with npm install, and using correct relative or absolute paths in require or import statements.
🔍

Why This Happens

This error occurs because Node.js cannot locate the module you are trying to use. It usually happens when the module name is misspelled, the module is not installed, or the file path is incorrect.

javascript
const express = require('expres'); // typo in module name
const myModule = require('./myModule.js'); // file does not exist
Output
Error: Cannot find module 'expres' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:...)
🔧

The Fix

Correct the module name spelling, install missing packages using npm install, and verify file paths are correct and relative to the current file.

javascript
const express = require('express'); // correct module name
const myModule = require('./myModule.js'); // ensure file exists in the same folder
Output
No error; modules load successfully
🛡️

Prevention

Always double-check module names and paths before running your code. Use npm install to add packages and keep package.json updated. Use relative paths starting with ./ or ../ for local files. Consider using a linter or editor with autocomplete to catch typos early.

⚠️

Related Errors

  • MODULE_NOT_FOUND: Happens when Node.js cannot find a package or file; fix by installing or correcting path.
  • SyntaxError in import/export: Use correct ES module syntax or set "type": "module" in package.json.

Key Takeaways

Check module names and file paths carefully to avoid 'Cannot find module' errors.
Install missing packages with 'npm install' before requiring them.
Use correct relative paths starting with './' or '../' for local files.
Keep your 'package.json' and 'node_modules' folder in sync.
Use tools like linters or IDE autocomplete to catch mistakes early.