NodeJS使用npm安装包提示:npm ERR! code EACCES syscall mkdir

错误描述

在 Linux / FreeBSD 系统中使用 npm 安装全局软件包:

npm install nrm -g

提示如下错误:

npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/nrm
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/nrm'
npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/nrm'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/local/lib/node_modules/nrm'
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: /home/anxin/.npm/_logs/2023-12-14T06_17_55_807Z-debug-0.log

错误原因

npm 对 node_modules 目录没有访问权限

解决方法

有两种方法解决使用npm为NodeJS安装软件包时提示: npm ERR! code EACCES syscall mkdir 错误:

  1. 使用root用户安装NodeJS软件包
  2. 修改node_modules目录访问权限

使用root用户安装NodeJS软件包

sudo npm install nrm -g --no-fund

修改node_modules目录访问权限

sudo chmod -R go=u /usr/local/lib/node_modules