I'm getting errors with npm
while trying to install/update packages without SU permissions on Linux.
The easy way to solve the problem is execute sudo npm install <package>
, but I'm not sure if it is a good idea.
Best way is to become the owner of .npm
folder, as I found into StackOverflow's questions and blog posts.
My question is: why run npm
as SU it isn't a good idea?
Running
npm
as a super user has a risk of running some untrusted code as a super user which can potentially mess with your entire system. Runningnpm
as an unprivileged user has a risk of running that code with less privileges and it won't be able to mess with the entire system - just with your own files (which can be equally bad, depending on how you look at it).What I often do and recommend is to install Node in your home directory instead of globally on the system if it's your own computer. That way you don't have to run with
sudo
orsu
fornpm
or even formake install
of Node itself.I run a lot of versions of Node that I compile from sources sometimes with different switches and the convention that I use is to install Node in versioned directories, either globally in
/opt
(but then you needsudo
) or locally in my home directory in~/opt
.I do it like this:
Then I create a symlink
~/opt/node
pointing to~/opt/node-v7.1.0
and I have:in my
.profile
or.bashrc
.That way I don't have to run as super user for installing Node or for running npm.
As a bonus I can quickly switch my default Node version just by changing the symlink, and at any time I can run any other version if I change the PATH or run Node with a full path like
~/opt/node-v7.0.0/bin/node
.I explained that installation process in more detail in my other answers:
I don't want to go into too much detail here since this answer is about why running
npm
as a superuser is not a good idea - this installation process is just one solution to not have to runnpm
as a superuser.Other options of setting your npm permissions to avoid running as a superuser are described in Fixing npm permissions in npm docs (thanks to RyanZim for pointing it out in the comments).