Search code examples
node.jsmacosnpminstallationsudo

how resolve "sudo npm install" issues on MacOS


Some time ago i've tried to update npm using sudo npm install on my Mac, so the update didn't work and now i can't Run any of my npm progects. after this problem i tried to solve it search some answers on npm forum, and i've found a discussion where a developer said "never use sudo npm install, in particular on MacOS". so my question is

  1. how can i fix this problem without Formatting my pc if possible
  2. why using sudo with npm command is a bad idea ?

I'm sorry for my bad english, but i try hard to do my best. thanks for your patience.


Solution

  • I wrote an article about this issue that also walks through some solutions to managing node/npm versions without using sudo: https://medium.com/@ExplosionPills/dont-use-sudo-with-npm-still-66e609f5f92

    I'll try to summarize here.

    First of all, if you're using MacOS, I highly recommend using homebrew to install system node if you haven't done so already. You should be able to run brew install node (which will also install npm and yarn) without using sudo assuming you've gone through the homebrew setup properly.

    If you want to manage multiple versions of Node, I highly recommend https://github.com/tj/n as a tool. nvm is also very popular, but I prefer n. I walk through how to install and manage n in my article, but someone has also created a tool to help you through this: https://github.com/mklement0/n-install.

    You can also take a look at this part of my 2015 article on the same topic to potentially help you with issues you might face from having run sudo npm install in the past. You might try sudo rm -rf node_modules in your project followed by npm install (without sudo).

    Similarly, you may have to do something akin to sudo rm -rf $(npm prefix -g)/{bin,lib/node_modules} in case you globally installed node modules with the wrong prefix. Just be aware that this will remove libraries you installed with sudo before, so you will have to install them again.

    In addition to the issues you're running into, a key reason why you shouldn't use sudo npm anything is because npm commands including install have the ability to run arbitrary scripts including ones that are downloaded from the registry. You don't want to give root permissions to something that runs arbitrary scripts!