Cannot find module is looking in a wrong directory

Viewed 1236

I've installed nodemon using npm i -g nodemon and this was installed in the global path which is:

C:\Users\John\AppData\Roaming

so I started a new project using npm i -y and created a simple index.js entry point using:

{
  "name": "scp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1"
  }
}

when I start the app using nodemon I got:

Error: Cannot find module 'C:\Program Files\nodejs\node_modules\nodemon\bin\nodemon.js'

as you can see the path is actually wrong, so I tried to change it using:

npm config set prefix C:\Users\John\AppData\Roaming
npm config get prefix

and this return:

C:\Users\John\AppData\Roaming

the problem's that when I start the app using nodemon I get the same error message 'cause the path is always wrong:

Error: Cannot find module 'C:\Program Files\nodejs\node_modules\nodemon\bin\nodemon.js'

how can I fix this?

4 Answers

Can you try to install nodemon in your current package.json using :

npm i --save nodemon

Then change your start script to

"start": "nodemon index.js"

Hope it works for you

Another issue that causes a similar error is using "&" anywhere in the path name. npm will install packages in the correct location ('foobar&foobar/myApp/node_modules' folder) but the path to some package files will be wrong. The fix is to rename the folder that has "&" (foobar&foobar --> foobarAndfoobar) and run the following where your node_modules packages are installed:

rm -rf node_modules
npm install

I hope this saves a headache for anyone who ran into my issue.

You can always put nodemon as dev dependency and specify it in the scripts section of your package.json. You don't need to install it globally when you need it.

Ex. (package.json)

 "scripts": {
    "start": "nodemon index.js"
  },

About your original problem... It has to be something with the configuration of your npm/node. I would suggest to use something like NVM that handles multiple npm/node instances and configurations locally. It's something I would always suggest to use to any developer who uses node.

Take a look at it https://github.com/coreybutler/nvm-windows And try with a local version of npm to understand where the problem comes from. Be aware that your current (global) node installation might be in conflict with the NVM one (bin Paths... etc etc) so you might need to use only npm/nodes that come from NVM and get rid of the global one.

Double-check if any of your directories has "&". Rename it and nodemon will work.. Broke my head for 1.5hrs.

Related