npm 命令报权限不足错误 Error EACCES permission denied

在使用 npm 命令安装组件的时候,经常会报 权限不足 的错误:Error: EACCES: permission denied ,虽然用 sudo 可以解决问题,但都只是暂时的;

错误信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR! { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR! stack:
npm ERR! 'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'access',
npm ERR! path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:

解决方法

  • 官方的解决方案

  • 里面有两种方法

  1. 重装 version manager
  2. 改变 npm 的默认路径

这里我选择了第 2

中文译

创建global安装任务的目录

1
mkdir ~/.npm-global

配置npm使用新的目录

1
npm config set prefix '~/.npm-global'

在~/.profile文件中增加配置

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

配置文件立即生效

1
source ~/.profile

重新执行命令

1
npm install -g xxxx