How to resolve “Cannot find module ‘commander’” error in Node.js

The commander package is a great utility for building a CLI, a lightweight, expressive, and powerful command-line framework for node.js. Still, when implementing the project, you will sometimes have problems using it. The most common mistake is the “Cannot find module ‘commander’” error in Node.js. Don’t be confused. I have some ways for you.

What causes the “Cannot find module ‘commander’” error in Node.js?

This error occurs when having not installed the module properly and trying to use 'commander' in the project by using the function: 

const { program } = require('commander');

The project’s module are listed in the file at the root of the project: package.json

You will see this following error inside the terminal.

Output:

> node index.js
Error: Cannot find module 'commander' 
Require stack:

How to fix this error?

Install module

To fix this error, simply install the missing module using the npm install command: 

npm install commander --save

You should use the cmd prompt for that particular folder, then run the program.

After that, restart your IDE.

If still error, let’s remove the entire folder and re-installing: 

rm -rf node_modules
npm install
nm install commander

Downgrade your Node version

Maybe your project needs a different node.js version. Try uninstalling the old version and reinstalling another one.

npm uninstall node
npm install [email protected]

@version is your specified version

And check node version: node -v

You can use NVM to manage multiple versions of Node which works like a charm.

Change where dependencies are placed

Check the package.json file if the module commander already existed looks like this:

"devDependencies": {
    "chalk": "^2.4.1",
    "commander": "^2.15.1",
    "download-git-repo": "^1.0.2",
    "handlebars": "^4.0.11",
    "inquirer": "^6.0.0",
    "log-symbols": "^2.2.0"
  }
    

I think the packages in the devDependencies are not sent to the npm. Now you try transferring them to dependencies.

"dependencies": {
    "express": "expressjs/express",
    "commander": "^2.15.1",
     …..
}

Summary

A little note for you when installing any module, write the correct syntax and make sure the connection is stable. You should check the package file and make sure the dependency is there. Because the error “Cannot find module ‘commander’” error in Node.js can happen from the simplest mistakes.

Hope the above will solve your problem. If you have any questions, please leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *