Introduction
While developing a Node.js application, you may encounter an error message such as Error: Cannot find module ‘express’ or Error: Cannot find module ‘./routes/user’. This error usually appears when Node.js cannot locate a module that your application is trying to load.
Modules help developers organize code into reusable files and packages. Node.js supports built-in modules, local modules, and third-party packages installed through npm. If a module is missing, its path is incorrect, or it has not been installed properly, the application may fail to start.
The Cannot Find Module error in Node.js is common among beginners and experienced developers. In this tutorial, you will learn why this error occurs, how to fix it, and how to prevent it in your projects.
What Is the Cannot Find Module Error in Node.js?
The Cannot find module error occurs when Node.js cannot resolve a module requested by your application.
For example:
const express = require("express");
console.log("Application started");
If Express is not installed in the project and cannot be resolved from the relevant module lookup paths, Node.js may display an error similar to this:
Error: Cannot find module 'express'
Require stack:
- /project/app.js
The exact output depends on your project structure and Node.js version.
In this example, Node.js attempts to load the express package, but it cannot find it.
The error can also occur with local JavaScript files:
const user = require("./user");
If the referenced file cannot be resolved, Node.js reports a module-loading error.
Why Does the Cannot Find Module Error Occur?
There are several reasons why Node.js may fail to locate a module.
1. The Package Is Not Installed
If your application imports a third-party package that has not been installed, Node.js cannot load it.
For example:
const express = require("express");
If Express is missing from the project’s dependencies, this import may fail.
2. The Module Path Is Incorrect
Local modules must be referenced using the correct relative or absolute path.
For example:
const user = require("./user");
This statement expects Node.js to resolve a module named user relative to the current file. If the file is located in another directory, the path must be updated.
3. The File Name Is Incorrect
File names and paths may behave differently across operating systems. A path that works on a case-insensitive file system may fail on a case-sensitive one.
For example, if the actual file is User.js, this import may fail on a case-sensitive system:
const user = require("./user");
Use the correct capitalization:
const user = require("./User.js");
4. Dependencies Were Not Installed
When you download or clone a Node.js project, its node_modules directory may not be included.
If the dependencies have not been installed, third-party imports can fail.
5. The Application Is Running from the Wrong Location
Running a script from an unexpected project directory can lead to confusion about file paths and package resolution.
Relative imports are resolved relative to the importing file, while package resolution searches locations based on Node.js module-resolution rules. Therefore, changing directories does not fix every path problem, but it is still important to verify that you are working with the intended project.
How to Fix the Cannot Find Module Error in Node.js
Let’s explore common solutions with practical examples.
1. Install the Missing Package
If Node.js cannot find a third-party package, install it using npm.
For example, if the error mentions express, open your terminal in the project’s root directory and run:
npm install express
Then use the package in your application:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to Node.js");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Run the application:
node app.js
If the installation succeeds and the project is configured correctly, Node.js should be able to resolve Express.
Important: Install the package in the project that runs the application, rather than assuming a package installed globally will be available to every project.
2. Check the Module Path
If the error refers to a local file, verify the file’s location and the path used in require().
Suppose your project has the following structure:
myapp/
├── app.js
└── user.js
The app.js file can import user.js like this:
const user = require("./user");
console.log(user.name);
The user.js file might contain:
const user = {
name: "Amit",
age: 25
};
module.exports = user;
Run the application:
node app.js
Output:
The ./ prefix indicates that the module is located relative to the current file.
If the module is inside a folder, include that folder in the path.
For example, with this structure:
myapp/
├── app.js
└── models/
└── user.js
Use:
const user = require("./models/user");
Check every directory and file name carefully.
3. Verify package.json
The package.json file stores information about a Node.js project, including its dependencies.
If your project already defines its dependencies, install them by running the following command in the project root:
npm install
For example, a package.json file might contain:
{
"name": "my-node-app",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
"express": "^5.0.0"
}
}
The version shown is an example. Your project may use a different compatible version.
After running npm install, npm installs the declared dependencies and creates or updates the node_modules directory and lockfile as needed.
If a package is not listed in the project’s dependencies, install it explicitly:
npm install package-name
Replace package-name with the actual package name.
4. Check File Name and Extension
Ensure that the imported file exists and that its name matches the import path.
For example, if your file is named database.js, use:
const database = require("./database.js");
For CommonJS modules, Node.js can often resolve the .js extension automatically, so require(“./database”) may also work.
However, explicitly writing the extension can make the intended file easier to identify.
Remember that .js, .json, and .node files have different roles in Node.js module loading. Do not assume that a file with a similar name or a different extension is interchangeable.
5. Remove and Reinstall Dependencies When Necessary
Sometimes, an installation may be incomplete or the node_modules directory may be inconsistent.
On macOS or Linux, you can remove the dependency directory and reinstall packages:
rm -rf node_modules
npm install
On Windows Command Prompt, use:
rmdir /s /q node_modules
npm install
Run these commands from the correct project directory.
Deleting node_modules removes installed packages from that project, so make sure you have the correct package.json and lockfile before doing so. Avoid deleting the lockfile unnecessarily, because it helps maintain consistent dependency versions.
6. Check CommonJS and ES Module Configuration
Node.js supports both CommonJS and ECMAScript modules. Mixing their syntax or using an incompatible module configuration can cause module-loading errors.
CommonJS example:
const path = require("path");
console.log(path.basename("/users/amit/file.txt"));
ES module example:
import path from "node:path";
console.log(path.basename("/users/amit/file.txt"));
For ES modules, use a suitable configuration, such as setting “type”: “module” in package.json or using the .mjs extension.
For example:
{
"type": "module"
}
In an ES module, a local import can look like this:
import user from "./user.js";
Notice that the file extension is included. Relative ES module imports generally require the explicit file extension.
If you see Cannot find module, first check whether the requested file or package exists. If you see errors such as require is not defined in ES module scope or ERR_MODULE_NOT_FOUND, also check the module system and import syntax.
7. Use require.resolve() to Debug Module Paths
Node.js provides require.resolve() to find the resolved path of a module without loading it.
This is useful when you are unsure where Node.js expects a package or local file to be located.
Example:
try {
const modulePath = require.resolve("express");
console.log("Module found at:", modulePath);
} catch (error) {
console.error("Module could not be resolved:", error.message);
}
If Express is available to the current module, Node.js prints the resolved file path.
Otherwise, the catch block displays the resolution error.
You can also use this approach with local modules:
console.log(require.resolve("./user"));
The path is resolved relative to the file containing this code, not simply relative to the terminal’s current directory.
Real-Life Example: Fixing a Missing Express Module
Imagine that you have downloaded a Node.js project and want to run its server.
Your project structure is:
myapp/
├── app.js
├── package.json
└── routes/
└── users.js
Your app.js contains:
const express = require("express");
const users = require("./routes/users");
const app = express();
app.use("/users", users);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
If Express has not been installed, the application may fail with:
Error: Cannot find module 'express'
To fix the issue, follow these steps:
Step 1: Open a terminal in the myapp directory.
Step 2: Install the project dependencies:
npm install
If Express is not declared in package.json, install it separately:
npm install express
Step 3: Verify that routes/users.js exists and exports a valid Express router. For example:
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.json([
{ id: 1, name: "Amit" },
{ id: 2, name: "Priya" }
]);
});
module.exports = router;
Step 4: Start the application:
node app.js
Step 5: Open the following URL:
http://localhost:3000/users
The application should return the user data as JSON.
This example demonstrates that both third-party packages and local modules must be resolvable for a Node.js application to start successfully.
Common Mistakes to Avoid
1. Installing a Package in the Wrong Directory
If you install a package in another project, the current application may still be unable to find it. Run npm commands from the intended project root.
2. Using an Incorrect Relative Path
Remember that ./user refers to a module relative to the importing file. Verify the directory structure before changing the path.
3. Ignoring Capitalization
File names that differ only by capitalization may work on one operating system and fail on another. Keep file names and imports consistent.
4. Assuming Every Module Must Be Installed Through npm
Built-in Node.js modules, such as fs and path, do not need to be installed through npm.
Use the appropriate built-in module import:
const fs = require("node:fs");
const path = require("node:path");
5. Mixing Module Systems Without Checking Configuration
CommonJS uses require() and module.exports, while ES modules use import and export. Check the project’s configuration and use compatible syntax.
6. Deleting package-lock.json Unnecessarily
The lockfile helps keep dependency versions consistent. Reinstalling dependencies usually does not require deleting it.
Best Practices to Prevent Module Errors
- Maintain an accurate package.json file.
- Commit the appropriate lockfile to version control.
- Run npm install after cloning or downloading a project.
- Verify relative paths and file names before running the application.
- Keep file name capitalization consistent across development and production environments.
- Use compatible CommonJS or ES module syntax.
- Install dependencies in the correct project directory.
- Use require.resolve() or Node.js error details to investigate unresolved modules.
- Test the application in an environment similar to production.
Conclusion
The Cannot Find Module error in Node.js occurs when the runtime cannot locate a requested package or file. Common causes include missing dependencies, incorrect relative paths, inconsistent file names, and incompatible module configuration.
To resolve the error, verify the module path, install missing packages, check package.json, and make sure the project uses the correct module system. Tools such as require.resolve() can also help identify the source of a problem.
By following these practices, you can troubleshoot module-loading errors more quickly and build Node.js applications that are easier to maintain and deploy.