linux npm全局安装权限不足问题的正确解决办法

相信很多人遇到过这个问题,在linux上,从官网安装nodejs和npm后,每次全局安装模块都会提示权限不足:

Deans-Air:~ deangibson$ npm install -g eslint
npm ERR! tar.unpack untar error /Users/deangibson/.npm/eslint/2.4.0/package.tgz
npm ERR! Darwin 15.3.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "eslint"
npm ERR! node v4.2.3
npm ERR! npm  v2.14.7
npm ERR! path /usr/local/lib/node_modules/eslint
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall mkdir

npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/eslint'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/eslint']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/local/lib/node_modules/eslint',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/eslint',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack: 
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:35:25',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:47:53',
npm ERR!      'FSReqWrap.oncomplete (fs.js:82:15)' ] }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/deangibson/npm-debug.log

问度娘是解决不了任何问题的(概率大于99%),度娘上面的解决方案都是改权限:

sudo chmod 777 /usr/bin/npm

这个解决不了任何问题,而且有隐患。
其实官网针对此问题早就有解决方案:https://docs.npmjs.com/getting-started/fixing-npm-permissions
最好的方案就是使用nvm:https://github.com/creationix/nvm/blob/master/README.md#installation
在linux上,一条命令搞定nvm安装:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.9/install.sh | bash
或者
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.9/install.sh | bash

然后,安装node,注意:如果你已经安装了node,不用卸载旧的,直接安装就好,nvm会替你管理版本的:
nvm install node

然后。。。就完了,这时你再npm i -g XXX都不会出任何问题

你可能感兴趣的:(linux npm全局安装权限不足问题的正确解决办法)