Error: cannot find module
occurs when you try to load a non-existent module in Node, either via ECMAScript Modules (ESM) or CommonJS module systems.
Error: Cannot Find Module in Node Explained
Error: cannot find module
occurs in Node when you attempt to load a non-existent module. The error can also be thrown for a number of other reasons, including:
- Attempting to import a third-party package you haven’t installed yet.
- Importing a local module with the wrong path.
- Running a Node script in the terminal, but the script doesn’t exist.
- Use Node standard libraries with TypeScript that haven’t been installed yet.
- The module’s package.json points to a non-existent entry file.
The error usually looks like this in the console:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '/var/www/scripts/app.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
Why Does “Error: Cannot Find Module” Occur?
The error: cannot find module might happen if you’re trying to:
- Import a third-party package you haven’t installed yet, either with npm or
yarn
. - Import a local module, but the path is wrong.
- Run a Node script in the terminal, but the script doesn’t exist or the path is wrong.
- Use Node standard libraries with TypeScript, but you haven’t installed the
@types
/node
package. - The module’s
package.json
has a main field pointing to an entry file that doesn’t exist.
First, let’s review what a module is and how module systems work.
In a module system, modules are the building blocks of an application. Node implements ESM and CommonJS module systems to let you organize your code as reusable components.
With modules, you can only expose the public interface of your components and keep the internal functionalities private. This is done by using a module.exports
for CommonJS modules, or export
for ES modules.
The following code is an example of a module, which has a function to determine whether a number is odd or not:
function isOdd(number) {
return number % 2 !== 0
}
// Make isOdd available to other scripts (and other modules)
module.exports = isOdd
And here’s how we import it into another script called index.js
:
// index.js
const add = require('./isodd.js')
console.log(isOdd(3))
// output: true
All the modules you use have an ESM or CommonJS export declaration.
How Do Module Systems Find Modules?
If the identifier passed to require()
or import()
is a reference to a file, it starts with /
, ../
, ./
, etc., in your file system, Node will load it from the respective path. Otherwise, it looks it up in the installed modules, inside the node_modules
directory.
If the module isn’t found, it raises the cannot find module
error.
How to Fix Error: Cannot Find Module in Node.js
There are several scenarios in which this error can happen. Let’s explore each.
Third-Party Packages
If you try to import a third-party module and get this error, and you’re sure the spelling is correct, you probably haven’t installed the package yet.
Imagine this is the code:
const axios = require('axios');
// Make an HTTP request with Axios
If I run this on my machine, I’ll get the cannot find module
error because I haven’t installed it yet. In my project directory where my package.json
resides, I’d have to install axios
package with npm
or yarn
, like so:
npm install axios
Local Modules
Imagine you have a set of utility functions kept in a JavaScript file named utils.js
. You want to import a function called getUrl()
from this utils.js
into your script:
const { getUrl } = require('utils')
// Do something here ...
But when you run npm run build
, the build fails:
ERROR in ./app/index.js 30:0-30
Module not found: Error: Can't resolve 'utils' in '/var/www/app'
Since utils
isn’t a reference to a local file, my bundler, Webpack, assumes it’s inside a node_modules
directory. The build fails because the utils
module isn’t an installed package.
So, what I need to do here is make it an absolute path by adding ./
to my identifier:
const { getUrl } = require('./utils.js')
// Do something here ...
Problem solved.
Fix the Casing
Sometimes the error occurs because the letter casing is off. File names on Mac and Windows are case-insensitive by default. This means ./Utils
and ./utils
both work on Mac and Windows, where you develop the app. However, it’ll break on a Linux file system, where file names are case-sensitive.
Running a Node Script
Another scenario reported by developers is when you run a script with the Node command. However, the respective file can’t be located, probably owing to a typo in the name or path.
Always double-check that the path is correct and the script exists. You can always take advantage of the terminal’s autocomplete feature by typing the initial letters and pressing the tab to let it complete the path for you.
node ./scriptName.js
Node and TypeScript
If you’re coding in TypeScript and you’re importing a built-in Node module like fs
, you might get an Error: Cannot find module 'fs’
, too.
You can fix the issue by installing @types/node
:
npm install @types/node --save-dev
Even though all packages in node_modules
or @types
of any enclosing folder are included in your compilation. However, it’s worth ensuring node is added under compileOptions.types
:
{
compilerOptions: {
types: [node, jest, express]
}
}
Missing entry file in package.json
: Each module has an entry file named index.js
by default, unless it’s changed in the module’s package.json
via the main
field.
{
name: utils
}
If you decide to change the main field to another entry file, like main.js
, you must ensure the file exists. Or if you rename or relocate that file in the future, remember to update the package.json
, too.
Missing entry file in package.json
has been reported by several users on Stack Overflow.
Importing a Module From the Global node_modules or a Separate Directory
Sometimes you might have to use a globally-installed package in your development environment.
If you try to load a globally-installed module in your project, you might get the cannot find module
error.
A workaround to this problem is using the npm
link command. If the package is installed globally, all you need to do is run the following command while in your project directory:
npm link package-name
npm
will create a symbolic link from the globally installed package name to the node_modules directory of your project, as if you’ve installed it with npm install package-name
.
If the module you want to use is a local file residing somewhere in your file system other than the global node_modules
. For example, if you’re developing a module, you’ll have to do it in a two-step process:
First, in the terminal, you need to change the directory to where the module resides and run the npm
link (without any parameter). As a result, a symlink is created in the global node_modules
that links to your local package.
npm link
After that, change the directory to your project directory, where you want to import the module, and run the following command:
npm link package-name
This will create a symbolic link from the globally installed package name to the node_modules
directory of your project.
Now, you can use the package as if it’s an installed third-party package.
What If Error: Cannot Find Module Persists?
If none of the above solutions worked for you, maybe you’re dealing with corrupted or incomplete installations. In that case, you can take the following steps:
Delete node_module
directory:
rm -rf node_modules
Delete package-lock.json
:
rm -f package-lock.json
Clear the npm
cache:
npm cache clean --force
Install the packages again:
npm install
This will make a clean install of all the dependencies listed in your package.json
file.
Frequently Asked Questions
What does error: cannot find module mean in Node?
Error: cannot find module
signifies that you’re trying to load a non-existent module in Node. The error looks like this:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '/var/www/scripts/app.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
What causes the error: cannot find module in Node?
There are a few common causes that will throw the error: cannot find module in Node. These include:
- Attempting to import a third-party package you haven’t installed yet.
- Importing a local module with the wrong path.
- Running a Node script in the terminal, but the script doesn’t exist.
- Use Node standard libraries with TypeScript that haven’t been installed yet.
- The module’s
package.json
points to a non-existent entry file.