How to Fix Node.js require() Error
In this tutorial, you'll learn about How to Fix Node.js require() Error. We cover key concepts, practical examples, and best practices.
The Problem
Node.js require() throws errors when the module cannot be found, exports are not what was expected, or circular dependencies cause partial module loading.
Quick Fix
Step 1: Use the correct relative path
A relative path must start with ./ or ../:
const config = require('config.js');
Error: Cannot find module 'config.js'
Add ./ for same-directory files:
const config = require('./config.js');
Step 2: Check module exports
If the module exports are different from what you expect:
// module.js
module.exports = { handler: () => {} };
// app.js
const { handle } = require('./module');
console.log(handle);
undefined
The property name is handler, not handle:
const { handler } = require('./module');
console.log(handler);
[Function: handler]
Step 3: Handle circular dependencies
Circular requires cause partial exports:
// a.js
const b = require('./b');
module.exports = { name: 'A', b };
// b.js
const a = require('./a');
module.exports = { name: 'B', a };
When b.js requires a.js, a.js has not finished exporting, so a in b.js is an empty object. Restructure to avoid circular dependencies.
Step 4: Use try/catch for optional dependencies
When a module may not be installed:
try {
const optional = require('optional-package');
} catch {
console.log('Optional package not found, using fallback');
}
Step 5: Check for JSON require issues
JSON files require require():
const data = require('./data.json');
console.log(data.name);
If the JSON is malformed, it throws a parse error. Validate the JSON file first.
Prevention
- Always use
./or../for local files. - Verify export names match the destructured properties.
- Restructure code to avoid circular dependencies.
- Use
module.exports = { ... }as a single assignment. - Test
require()calls in isolation during development.
Common Mistakes with require error
- 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
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch 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