错误!代码 EACCES, npm install --global yarn 遇到错误

npm ERR! code EACCES, npm install --global yarn met error

Mac 迷你 (M1, 2020)

蒙特雷

布朗尼 v1.17.2

nodejs v16.13.4

我正在根据参考学习solidity(https://www.youtube.com/watch?v=M576WGiDBdQ&t=25510s)。

Node.JS 安装没问题

当我尝试这个时

npm install --global 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/liwei/.npm/_logs/2022-01-08T12_13_37_765Z-debug.log
(base) liwei@liweideMac-mini-2 com~apple~CloudDocs % 

我检查了文件的所有者,所有者是 root,我应该使用 sudo 吗?

(base) liwei@liweideMac-mini-2 com~apple~CloudDocs % ls -l /usr/local/lib/node_modules/npm
total 64
-rw-r--r--    1 root  wheel  9742 10 14 08:49 LICENSE
-rw-r--r--    1 root  wheel  4190 10 19 06:36 README.md
drwxr-xr-x    9 root  wheel   288 12  1 19:46 bin
drwxr-xr-x    4 root  wheel   128 12  1 19:46 docs
-rw-r--r--    1 root  wheel   145 11 23 14:00 index.js
drwxr-xr-x   77 root  wheel  2464 12  1 19:46 lib
drwxr-xr-x    5 root  wheel   160 12  1 19:46 man
drwxr-xr-x  188 root  wheel  6016 12  1 19:46 node_modules
-rw-r--r--    1 root  wheel  6007 12  1 19:13 package.json
drwxr-xr-x    3 root  wheel    96 12  1 19:46 tap-snapshots
(base) liwei@liweideMac-mini-2 com~apple~CloudDocs % 

找到这个帖子(),更换了所有者,仍然一个文件不要改变。

(base) liwei@liweideMac-mini-2 com~apple~CloudDocs % sudo chown -R liwei: /usr/local/lib/node_modules 
(base) liwei@liweideMac-mini-2 com~apple~CloudDocs % ls -la /usr/local/lib/node_modules              

total 0
drwxr-xr-x   4 liwei  wheel  128  1  8 11:51 .
drwxr-xr-x   4 root   wheel  128  1  8 11:51 ..
drwxr-xr-x   7 liwei  wheel  224 12  1 19:46 corepack
drwxr-xr-x  13 liwei  wheel  416 12  1 19:46 npm

这2个点是什么?

参考答案在这里 ()

这对我来说很快。

为了尽量减少权限错误的可能性,您可以将 npm 配置为使用不同的目录。在此示例中,您将在主目录中创建和使用隐藏目录。

备份您的计算机。在命令行上,在您的主目录中,为全局安装创建一个目录:

mkdir ~/.npm-global

配置 npm 以使用新的目录路径:

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

在您喜欢的文本编辑器中,打开或创建一个

~/.profile

文件并添加这一行:

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

在命令行上,更新您的系统变量:

source ~/.profile

要测试您的新配置,请在不使用 sudo 的情况下全局安装包