Mac下执行npm install -g json-server时出现rename系统调用权限错误
Mac 全局安装 json-server 遇 EACCES 权限错误解决方法
错误信息
(node:34559) ExperimentalWarning: CommonJS模块/usr/local/lib/node_modules/npm/node_modules/debug/src/node.js正在使用require()加载ES模块/usr/local/lib/node_modules/npm/node_modules/supports-color/index.js。 require()加载ES模块的支持是实验性功能,可能随时变更 (使用`node --trace-warnings ...`查看警告产生位置) npm error code EACCES npm error syscall rename npm error path /usr/local/lib/node_modules/json-server npm error dest /usr/local/lib/node_modules/.json-server-SmlbN4FS npm error errno -13 npm error Error: EACCES: 权限被拒绝,重命名 '/usr/local/lib/node_modules/json-server' 至 '/usr/local/lib/node_modules/.json-server-SmlbN4FS' npm error at async Object.rename (node:internal/fs/promises:784:10) npm error at async moveFile (/usr/local/lib/node_modules/npm/node_modules/@npmcli/fs/lib/move-file.js:30:5) npm error at async Promise.allSettled (index 0) npm error at async [reifyPackages] (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:325:11) npm error at async Arborist.reify (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:142:5) npm error at async Install.exec (/usr/local/lib/node_modules/npm/lib/commands/install.js:150:5) npm error at async Npm.exec (/usr/local/lib/node_modules/npm/lib/npm.js:207:9) npm error at async module.exports (/usr/local/lib/node_modules/npm/lib/cli/entry.js:74:5) { npm error errno: -13, npm error code: 'EACCES', npm error syscall: 'rename', npm error path: '/usr/local/lib/node_modules/json-server', npm error dest: '/usr/local/lib/node_modules/.json-server-SmlbN4FS' npm error } npm error npm error 操作被操作系统拒绝。 npm error 很可能当前用户没有访问该文件的权限 npm error npm error 若您认为这是权限问题,请仔细检查文件及其所在目录的权限,或以root/管理员身份重新运行命令。 npm error 本次运行的完整日志可在以下路径查看:/Users/fllap0630_mayurpatil/.npm/_logs/2024-12-05T17_07_36_861Z-debug-0.log
核心问题
当前用户无权限修改系统级目录/usr/local/lib/node_modules,导致npm无法完成文件重命名操作。上方的ExperimentalWarning属于Node.js模块加载的实验性提示,不影响安装,可忽略。
解决方法
方法1:临时提权安装
直接用sudo获取管理员权限执行安装命令:
sudo npm install -g json-server
输入用户密码后即可完成安装。此方法快捷但不推荐长期使用,易引发后续全局包权限冲突。
方法2:配置用户专属全局npm目录
- 创建用户私有全局目录:
mkdir -p ~/.npm-global
- 设置npm使用该目录作为全局包存储路径:
npm config set prefix '~/.npm-global'
- 将该目录添加到系统环境变量(zsh编辑
~/.zshrc,bash编辑~/.bash_profile):
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
- 刷新配置使修改生效:
source ~/.zshrc
- 再次执行安装命令:
npm install -g json-server
方法3:使用nvm管理Node.js(推荐长期方案)
nvm会将Node.js和npm安装在用户目录下,从根源避免系统权限问题:
- 安装nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
- 刷新shell配置:
source ~/.zshrc
- 安装长期支持版Node.js:
nvm install --lts
- 设置默认使用该版本:
nvm alias default lts/*
- 执行安装命令:
npm install -g json-server
内容的提问来源于stack exchange,提问作者Mayur Patil
相关产品推荐
相关产品推荐

