How to Fix Node.js Module Not Found Error
In this tutorial, you'll learn about How to Fix Node.js Module Not Found Error. We cover key concepts, practical examples, and best practices.
The Problem
Node.js throws Error: Cannot find module 'X' when require() or import cannot locate the module, due to missing installations, incorrect paths, or package.json misconfiguration.
Quick Fix
Step 1: Install the missing module
The most common cause is a missing dependency:
const express = require('express');
Error: Cannot find module 'express'
Install it:
npm install express
Step 2: Check the require path
A relative path must start with ./ or ../:
const utils = require('utils/helpers');
Error: Cannot find module 'utils/helpers'
Node looks in node_modules first. For local files, use a relative path:
const helpers = require('./utils/helpers');
Step 3: Check the package.json exports field
Some packages define exports that limit what can be imported:
const internal = require('package/dist/internal');
Error: Cannot find module 'package/dist/internal'
Check the package's package.json exports:
{
"exports": {
".": "./index.js",
"./utils": "./dist/utils.js"
}
}
Use only the exported paths.
Step 4: Verify node_modules and package.json
Check that the module exists in node_modules:
ls node_modules/express
If missing, delete node_modules and reinstall:
rm -rf node_modules package-lock.json
npm install
Step 5: Check for ESM vs CJS mismatch
A module using ES modules cannot be required with require:
// This fails for ESM packages
const pkg = require('esm-only-package');
Use dynamic import instead:
const pkg = await import('esm-only-package');
Or set "type": "module" in your package.json and use import syntax.
Prevention
- Always run
npm installafter cloning a project. - Use
npm ls <package>to verify a package is installed. - Use
require.resolve('<package>')to debug path resolution. - Lock Node.js and npm versions with
.nvmrcandenginesin package.json. - Use
npm ciin CI environments for reproducible installs.
Common Mistakes with modulenotfound
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro