Node gyp ERR - invalid mode: 'rU' 解决方法
问题描述
在运行 yarn install
时,许多开发者(尤其是 MacOS Ventura/M1 用户)会遇到如下错误:
sh
File .../gyp/input.py", line 234, in LoadOneBuildFile
build_file_contents = open(build_file_path, 'rU').read()
ValueError: invalid mode: 'rU' while trying to load binding.gyp
gyp ERR! configure error
根本原因:新版本 Python(≥3.11)移除了 'rU'
文件读取模式,而旧版 node-gyp(v8 之前)仍在代码中使用此模式。这导致兼容性问题。
解决方案
✅ 方法一:使用兼容的 Python 版本(推荐)
Python 3.10 被确认与 node-gyp 完全兼容。通过环境变量指定 Python 路径:
bash
# M1 Mac 使用 Homebrew 安装 Python 3.10
brew install python@3.10
# 临时生效(仅当前终端)
export PYTHON=/opt/homebrew/bin/python3.10
# 永久生效(添加到 shell 配置)
echo 'export PYTHON=/opt/homebrew/bin/python3.10' >> ~/.zshrc
source ~/.zshrc
验证安装
检查 Python 版本是否生效:
bash
python --version # 应显示 Python 3.10.x
✅ 方法二:升级 node-gyp 版本
若依赖库(如 prebuild
)使用了旧版 node-gyp:
手动将 node-gyp 升级至 v9+:
bashnpm install node-gyp@latest --save-dev
在
package.json
中覆盖子依赖版本(需 npm ≥8.3):json{ "devDependencies": { "node-gyp": "^9.4.0" }, "overrides": { // 替换为实际报错的包名(如 prebuild) "problem-package": { "node-gyp": "$node-gyp" } } }
⚠️ 方法三:临时修改 node-gyp 源码(不推荐)
紧急情况下可以手动修改文件:node_modules/node-gyp/gyp/pylib/gyp/input.py
diff
- build_file_contents = open(build_file_path, 'rU').read()
+ build_file_contents = open(build_file_path, 'r').read()
注意
此修改在重新安装依赖后会失效,仅作为临时手段。
方法四:通过 Conda 创建隔离环境
适合需要同时管理多版本 Python 的场景:
bash
# 安装 Miniconda
brew install miniconda
# 创建 Python 3.10 环境
conda create -n py310 python=3.10
# 激活环境
conda activate py310
# 运行安装
yarn install
总结
解决方案 | 适用场景 | 长期稳定性 |
---|---|---|
切换 Python 3.10 | 项目无更高 Python 依赖 | ★★★ |
升级 node-gyp | 可控制依赖链 | ★★★★ |
修改源码 | 紧急修复 | ★ |
Conda 虚拟环境 | 需同时兼容多版本 Python | ★★★★ |
最佳实践建议:
- 开发环境 → 优先切换 Python 3.10 或使用 Conda 隔离
- 生产部署 → 升级依赖链中的 node-gyp 版本以彻底解决问题
- 避免操作 → 全局降级系统 Python(会导致其他工具异常)
可通过
node-gyp -v
检查版本,≥v8.0.0 已修复此问题。