如何修复 npm 错误 EACCES:权限被拒绝?

How do I fix the npm error EACCES: permission denied?

我尝试以安装 npm install -g pnpm 作为要求来启动一个项目,我尝试了 npm install 但它确实有效。但是 npm install -g pnpm 显示如下错误;以下来自终端!

npm ERR! code EACCES
npm ERR! syscall symlink
npm ERR! path ../lib/node_modules/pnpm/bin/pnpm.cjs
npm ERR! dest /usr/bin/pnpm
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, symlink '../lib/node_modules/pnpm/bin/pnpm.cjs' -> '/usr/bin/pnpm'
npm ERR!  [OperationalError: EACCES: permission denied, symlink '../lib/node_modules/pnpm/bin/pnpm.cjs' -> '/usr/bin/pnpm'] {
npm ERR!   cause: [Error: EACCES: permission denied, symlink '../lib/node_modules/pnpm/bin/pnpm.cjs' -> '/usr/bin/pnpm'] {
npm ERR!     errno: -13,
npm ERR!     code: 'EACCES',
npm ERR!     syscall: 'symlink',
npm ERR!     path: '../lib/node_modules/pnpm/bin/pnpm.cjs',
npm ERR!     dest: '/usr/bin/pnpm'
npm ERR!   },
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'symlink',
npm ERR!   path: '../lib/node_modules/pnpm/bin/pnpm.cjs',
npm ERR!   dest: '/usr/bin/pnpm'
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.
  1. 备份您的计算机。

  2. 在命令行中,在您的主目录中,为全局安装创建一个目录:

mkdir ~/.npm-global
  1. 配置 npm 以使用新的目录路径:
npm config set prefix '~/.npm-global'
  1. 在您首选的文本编辑器中,打开或创建一个 ~/.profile 文件并添加以下行:
export PATH=~/.npm-global/bin:$PATH

  1. 在命令行中,更新您的系统变量:
source ~/.profile

  1. 要测试您的新配置,请在不使用 sudo 的情况下全局安装包:
npm install -g pnpm

来源: https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally