How To Solve Cannot find module error using Node.js – Definitive Guide

Common Js Modules are the way to package JavasScript code for Node.js.

You can use npm install <moduleName> to get the module installed in your project to solve Cannot find module error using Node.js

Cause of Error
Cannot find module error occurs when Node fails to locate a module in node directory at runtime.

Solution
You can install the missing module or place it in its respective location to solve the Cannot find module error using Node.js.

 npm install express

There are a couple of ways this error can occur, and let us see how to solve the Cannot find module error using Node.js in detail.

Install the missing module

You need to install a package before using that package in your code. If you have not installed a package, it leads to a Cannot find module error.
Code

    //index.js
    const  express = require( 'express');
    const  app = express();
    app.get('/', (req, res) => {
        res.send('Welcome To Tech Mam!!!')
    });
    app.listen(3000);
    //current package structure
    . 
    ├── node_modules/ 
    │   └── lodash 
    ├── index.js 
    ├── package-lock.json 
    └── package.json
    node .\index.js              

Output

    node:internal/modules/cjs/loader:936
      throw err;
      ^
    Error: Cannot find module 'express'
    Require stack:
    - C:\Node\index.js
    at Function.Module._resolveFilename ... {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
      'C:\\Node\\index.js'
    ]
}

The node_modules package structure doesn’t have an express package, and the node will return Cannot find module error on loading that module.

You must install the package and load it later to resolve this issue.

Code

    npm install express 

(or)

    npm install express --save     

added 57 packages, and audited 59 packages in 10s
Seven packages are looking for funding
run npm fund for details
found 0 vulnerabilities

    //current package structure
    . 
    ├── node_modules/ 
    │   └── express
    │   └── lodash 
    │   └── ...
    ├── index.js 
    ├── package-lock.json 
    └── package.json

Output

    node .\index.js
    http://localhost:3000/              //hit local server in browser
    Welcome To Tech Mam!!!              //response printed on webpage

Once the npm install is successful, it adds the package to node_modules and is ready to use.

Verify the path of user-defined modules

Importing user-defined modules should be done carefully because, if the right path specification is not given, it will lead to a Cannot find module error using Node.js.

Code

    //index.js
    const  home = require('main');      //importing module
    console.log(home('TechMam!!!'));

    //main.js
    module.exports = function  getWelcomeText(name) {
        return  `Welcome to ${name}`;
    }               
    //current package structure
    . 
    ├── node_modules/ 
    │   └── ...
    ├── index.js 
    └── main.js 
    node index.js

Output

    node:internal/modules/cjs/loader:936
      throw err;
      ^
    Error: Cannot find module 'main.js'
    Require stack:

In the above index.js file, importing the module path of the file require(‘main‘); is not specified correctly, and that leads to cannot find module error.

You need to specify the proper path to get this fixed.
Code

    //index.js
    const  home = require('./main');        //importing module
    console.log(home('TechMam!!!'));                   
    node index.js 

Output

    Welcome to  TechMam!!!

Let’s see one more example if the file is present in a different directory like below,

    . 
    ├── node_modules 
    ├── home/ 
    │ └── main.js 
    └── index.js

You have to update the complete path from the root directory.

    //index.js
    const  home = require('./home/main');       //importing module
    console.log(home('TechMam!!!'));

Update the Package.json with correct information

Package.json file contains start property specified inside script property.
If the file specified in the start property is moved or removed from the location, you will get a “Cannot find module error”.

Code

    //package.json
    {
        "name": "TechMam",
        "version": "1.0.0",
        "description": "TechMam Tutorials",
        "main": "index.js",
        "scripts": {
            "start": "node index.js"
        },
        "author": "sv",
        "dependencies": {
            "express": "^4.18.1"
        }
    }

    //current project structure
    . 
    ├── node_modules 
    ├── home/ 
    │ └── index.js 
    └── package.json
    npm start

Output

    node:internal/modules/cjs/loader:936
      throw err;
      ^

    Error: Cannot find module 'C:\Node\index.js'

In the above package.json code, the start property is configured with node index.js, but the index.js file is not present under the root directory and is the reason for the error.
So either you have to place index.js under the root directory or update the path in the package.json(node home/index.js)

    //updated project structure
    . 
    ├── node_modules 
    ├── home 
    ├── index.js 
    └── package.json

Note
Cannot find module error can also occur if the main property in package.json contains an incorrect file path.
The main attribute is the primary entry point for your program. If the main attribute is not set, then index.js will act as the primary entry point.

Link package from global node_modules to local node_modules

You can install the package in the global node_module scope and link the package to your local node_modules.
If you don’t Link the module in the global scope to local node_modules, you will encounter a Cannot find module error.
Code

    //index.js
    const  express = require( 'express');
    const  app = express();
    app.get('/', (req, res) => {
        res.send('Welcome To Tech Mam!!!')
    });
    app.listen(3000);
    //current package structure
    . 
    ├── node_modules/ 
    │   └── lodash 
    ├── index.js 
    ├── package-lock.json 
    └── package.json
    npm i -g express
    node .\index.js

Output

    > node index.js
    node:internal/modules/cjs/loader:936
      throw err;
      ^
    Error: Cannot find module 'express'
    Require stack: ...                  

If a package is installed with global scope, you need to link it to local node_modules using the npm link.
Code

    npm link express  
    node .\index.js                                   

Output

    http://localhost:3000/              //hit local server in browser
    Welcome To Tech Mam!!!              //response printed on webpage

Remove node_modules and re-run npm install

Sometimes, the npm package installation may be incomplete or crash, leading to a Cannot find module error.

You can remove the node_modules directory and package-lock.json and try re-installing using the npm install.
Code

    rm -rf node_modules package-lock.json

The above command will remove both node_modules and package-lock.json.

    npm install

Uninstall Node.js and re-install the Node.js application

You may also get a Cannot find module error due to Incomplete/Bad Node.js installation.

You would require clean Node.js installation in windows; follow the below steps,

  • Uninstall the current Node.js
  • Delete npm and npm_cache folders in “C:\Users\user\AppData\Roaming”
  • Restart windows and install Node.js
  • Run npm init -y` to initialize the default configuration.
  • Set the environment path for NODE_PATH. Path to your installed packages. Mostly path looks like NODE_PATH = C:\Users\\<“user”>\AppData\Roaming\npm\node_modules or C:\Users\<“user”>\node_modules.
  • Now start a new command console and run npm without any issues.

Summary

You have learned to Solve the Cannot find module error using Node.js.

The Common Js modules are the way to package JavaScript code in the Node.js application.

You have also learnt about the multiple possible ways to get a Cannot find module error using Node.js and its solutions.

You May Also Like

Leave a Comment