Debugging npm - "Error: Cannot find module xxx"

11 January 2016

I recently had an issue where a CoffeeScript unit test I had written started throwing “Error: Cannot find module”. Here are the steps I used to resolve the issue.

TL;DR

Steps to try to resolve the issue:

  1. Ensure the module is installed.
  2. Clean the cache.
  3. Remove the node_modules directory and reinstall.
  4. Check the package version number. Is it what you expected? Does a previous version of the package work?

Detailed steps

  1. Ensure the module is installed using the command: npm list package_name. This will need to be run in the project’s directory, which should have a node_modules directory and package.json file in it.
  2. Try cleaning the cache by using the command npm cache clean. Aside: you can see where your cache is located with the command npm config get cache.
  3. If that does not resolve the issue, npm may have gotten in a funk so try reinstalling the modules. In your project directory do the following:
    • rm -rf node_modules - this deletes the node_modules directory and all its content.
    • npm cache clean - deletes the contents of the npm cache directory.
    • npm install - reinstall all the packages for your project from it’s package.json file.
  4. If that does not resolve the issue, check if the package has recently been updated. If the versioning in the package.json file uses version ranges then a new version of the package may have been pulled recently. Check to see if that new version is actually valid. Does the process work if you use a previous version?

The final step is what resolved my issue for me. I was using version ranges in my package.json and had inadvertently obtained a new version of the package, which was broken.

The kofi logo of a coffee mugLike this? Please buy me a coffee!

Share