npm / yeoman install generator-angular without sudo

I tried to install generator-angularjs using Yo (Yoeman) without sudo:

npm install -g generator-angular

I get:

Error: EACCES, mkdir '/usr/lib/node_modules/generator-angular'

When I type in sudo yo, yo tells me that I should not use sudo (which is perfectly understandable).

I have a ~/node_modules directory - why doesn't yo install its packages there?


Solution 1:

Generators are designed to be installed globally. Otherwise, you always have to install the generator you're about to use in each project, which is unnecessarily painful. Also, you don't get to see the lovely yo menu which lists you all the available generators (unless of course, you install them all locally):

yo

Setting up npm for global installation

So, how do we get npm to install packages globally? As you correctly said, you should never, ever run yo with sudo. There are lots of different solutions to this problem and you can spend hours discussing their pros and cons religiously.

I personally dislike installing my user packages into the global /usr/ folder. /usr/ is for software that is shared across all users on the computer. Even if it's only using the machine, there are still good reasons to respect the way the Unix file system hierarchy is designed. For example if you decide at one point to wipe your whole node installation.

My preferred way of enabling npm to install packages globally without breaking out of $HOME is to set a local node prefix. This is as easy as running

echo 'prefix = ~/.node' >> ~/.npmrc

in your local shell. After that, you want to adjust your $PATH, to point to the new installation destination for global node executables by adjusting your favorite shell's config. E.g. by adding

export PATH="$PATH:$HOME/.node/bin"

to your ~/.bashrc. After that, you can happily run npm install -g generator-angular without sudo, without running into permission conflicts and if something is completely broken and you want to start from scratch, all you need to do is remove your ~/.node directory.

Solution 2:

Thanks to @passy I managed to finally get this working on ubuntu 13.04 (in case anyone is having similar set up issues) with the following :

sudo apt-get update
sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

trying to run:

npm install -g yo

resulted in

Error: EACCES, mkdir '/usr/lib/node_modules/yo'

Fixed using:

echo prefix = ~/.node >> ~/.npmrc
echo 'export PATH=$HOME/.node/bin:$PATH' >> ~/.bashrc 
. ~/.bashrc

Running:

yo webapp

resulted in:

Error: EACCES, permission denied '/home/username/.config/configstore/update-notifier-yo.yml'

Fixed using:

sudo chown yourusername:yourusername /home/yourusername/.config/configstore/update-notifier-yo.yml