解决mac ubuntu每次npm install都需要sudo的权限错误问题 - maggie03230/maggie03230.github.io GitHub Wiki

参考文章:

http://www.johnpapa.net/how-to-use-npm-global-without-sudo-on-osx/

大体解决思路及命令:

1.把npm全局包的文件夹移到自己的用户文件夹:
npm config set prefix ~/npm

2.把npm的path指向刚才改的位置:

# open your .bashrc (Linux) or .bash_profile (Mac) file for editing:
nano ~/.bashrc # for Linux
# or...
nano ~/.bash_profile # for Mac if you haven't created a .bashrc file

# add these lines:
export PATH="$PATH:$HOME/npm/bin"
export NODE_PATH="$NODE_PATH:$HOME/npm/lib/node_modules"

# save the file and then enter this command to make the changes take effect:
. ~/.bashrc
# or...
. ~/.bash_profile

3.把npm的权限赋给自己(需要sudo)

# optionally check to see if anything is owned by root:
ls -la ~/.npm

# take ownership of everything in your ~/.npm directory (must be run with sudo):
sudo chown -R $USER:`id -g -n $USER` ~/.npm

4.重新安装那些global的包

# no sudo necessary :)
npm install -g bower
npm install -g grunt-cli
npm install -g gulp
npm install -g yo