超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied
作者:mmseoamin日期:2023-12-21

在日常开发过程中,我们使用MAC执行 npm install -g 下载安装包的时候,经常会遇到如下报错:permission denied

报错详情
xxx@CN_C02xxxxx6M ~ % npm install -g yarn
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/yarn
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/yarn'
npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/yarn'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/local/lib/node_modules/yarn'
npm ERR! }
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.
npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/xxxxx/.npm/_logs/2022-12-06T11_15_27_852Z-debug-0.log

解决方案如下:

解决报错方案一:(针对正常权限的电脑)

sudo npm i yarn -g

解决报错方案二:(仅限电脑权限管控严格情况下,无法获取权限)

step1: 查看npm 全局文件安装地址
XXX@CN_CXXXMD6M ~ % npm list -g                    
/usr/local/lib
├── @quasar/cli@1.3.2
├── corepack@0.14.1
├── npm@8.19.2
└── yarn@1.22.18
step2: 从其他人电脑上同样的目录,拷贝出来两份文件,一个是命令的快捷方式文件,一个是环境变量所指的路径文件,粘贴到自己电脑相同位置
  • 命令快照文件

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第1张

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第2张

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第3张

  • 全局命令所指文件

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第4张

    step3: 打开环境变量配置文件,配置环境变量
    vim ~/.bash_profile
    

    把下面内容粘贴到环境变量文件里,

    export PATH=/usr/local/lib/node_modules/yarn/bin/:$PATH
    

    保存.bash_profile的编辑,执行一下文件

    source ~/.bash_profile
    
    问题解决,大功告成

    命令行重新打开,就可以使用yarn

    yarn -v
    

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第5张

    解决方案三:(建议大家都使用这种方案)

    step1: 打开环境变量配置文件,配置环境变量
    mkdir ~/.npm-global
    npm config set prefix '~/.npm-global'
    
    step2: 打开环境变量配置文件,配置环境变量
    vim ~/.bash_profile
    

    把下面内容粘贴到环境变量文件里,

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

    保存.bash_profile的编辑,执行一下文件

    source ~/.bash_profile
    

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第6张

    step3: 问题解决,大功告成

    命令行重新打开,就可以使用yarn

    超详细手把手教你四种方案彻底解决MAC npm install -g 报错permission denied,第7张

    解决方案四:

    step1:前提-已经安装homebrew

    (如果未安装,可以打开终端,输入以下命令安装Homebrew)

    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    
    step2:查看安装的brew的版本
    brew --version 
    
    step3:使用brew去安装我们需要的包,这里以yarn为例
    brew install yarn
    

    原理

    报这个错,根本原因是由于npm全局安装模块的默认路径没有权限,通常有以下几种方式解决: