Insall node and npm with no sudo

I’ve been using node and his good buddy npm for a couple of years now. Up until three days ago, I would happily prefix sudo whenever an npm package gave me an EACCESS error. I’ve always known this is bad practice, but had never encountered an issue. This all changed when I attempted something fairly mundane: Deploy a Hexo blog with Capistrano.

For better or worse, my Capistrano deployment runs npm install as part of its routine. I tried mucking around with sudo and visudo, but to no avail. The blog would simply not deploy because of the restrictive sudo npm install step. At some point it finally occurred to me that npm shouldn’t need sudo anyway, so I’d best fix the problem properly. Instead I did a quick hack on my production server:

The quick hack

Just kidding, this is actually legit, especially given that I’m the only one able to muck around in production. The following is adapted from here. Basically, it allows you to use the -g option without sudo, because all global npm packages get stored under your home directory:

1
2
3
mkdir ~/npm-global
npm config set prefix '~/npm-global'
vim ~/.profile

Append the following to the ~/.profile just opened (or created):

1
export PATH=~/npm-global/bin:$PATH

Now update your system variables:

1
source ~/.profile

Install something globally to make sure it works:

1
npm install -g jshint

A nicer way, arguably

This is more appropriate for a production environment with multiple users. It is adapted from here.

Create a new group:

1
sudo groupadd nodegrp

Add current user to the group (with logname)

1
sudo usermod -a -G nodegrp `logname`

Get access to group:

1
newgrp nodegrp

You can check to see that the user has been added by running:

1
groups

Change group ownership on all the critical components:

1
2
3
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

On existing installs

After fixing the issue, there’s a real good chance that root still owns some of the packages installed in the user’s home directory. That’s easy to fix:

1
sudo chown -R $(whoami):$(whoami) ~/.npm