DEV Community

sunflowerseed
sunflowerseed

Posted on

Don't run `sudo npm install -g` -- the simplest way to make it work

When we do

npm install --global something
Enter fullscreen mode Exit fullscreen mode

we may get permission errors. Some solution is to use sudo with that line, but it can be dangerous to let go of the full control of your computer to some npm install process.

There is one simple solution

mkdir ~/.my-npm-global
npm config set prefix '~/.my-npm-global'
Enter fullscreen mode Exit fullscreen mode

and then, add this line to both your ~/.profile and ~/.bashrc:

# add to both .profile and .bashrc
export PATH=~/.my-npm-global/bin:$PATH
Enter fullscreen mode Exit fullscreen mode

and then, either quit the Bash shell or just start a new one by typing bash.

And now we can do the installation line above, the shorthand:

npm i -g something
Enter fullscreen mode Exit fullscreen mode

Some notes

  1. We actually should only add to .profile, instead of .bashrc. But if we don't care about remote login, that's ok. We can even just add it to .bashrc in that case. (see reference 2 below)
  2. Otherwise, if we care of make it all perfect, then that line should be only added to .profile, but then we will need to reboot our computer
  3. Or we can add it to our .bashrc also, and then remove it next time after a reboot

Reference:

  1. https://stackoverflow.com/questions/33725639/npm-install-g-less-does-not-work-eacces-permission-denied
  2. https://superuser.com/questions/183870/difference-between-bashrc-and-bash-profile

Top comments (0)