Resolving node-gyp "invalid mode: 'rU'" Error on Python 3.11
Problem Statement
When running yarn install or npm install, you encounter this error:
bash
ValueError: invalid mode: 'rU' while trying to load binding.gyp
gyp ERR! configure errorThis occurs because old versions of node-gyp (v8.x and below) use deprecated Python syntax that's incompatible with Python 3.11. When newer Python versions attempt to run the outdated node-gyp code, they reject the 'rU' file-read mode.
Common environment factors:
- macOS Ventura+ (Apple Silicon M1)
- Python ≥3.11 installed
node-gyp<8.0.0 (or dependencies using oldnode-gyp)- Node.js 16+
Recommended Solutions
1. Downgrade Python to 3.10 (Quick Fix)
Install Python 3.10 and configure your system to use it:
bash
# Homebrew (macOS)
brew install python@3.10
# Set environment variable
export PYTHON=/opt/homebrew/bin/python3.10 # M1 path (Intel: /usr/local/bin/python3.10)
# Verify
python --version # Should show 3.10.xRun your package install after setting the variable.
2. Force node-gyp Update (Best Permanent Fix)
Update node-gyp to v9.0.0+ in your project:
- Install latest
node-gypbashnpm install --save-dev node-gyp@latest - Force dependencies to use the updated version via
package.json:json{ "overrides": { "node-gyp": "$node-gyp" } }
3. Set Compatibility Environment Variables
Point node-gyp to Python 3.10 without permanent downgrades:
bash
export NODE_GYP_FORCE_PYTHON=/opt/homebrew/bin/python3.10or
bash
# One-time session override
export PYTHON=/opt/homebrew/bin/python3.104. Fix Node-Gyp Source Code (Fallback)
Edit input.py to remove problematic syntax:
- Locate file:bash
find node_modules -type f -name "input.py" - Change line:python→
build_file_contents = open(build_file_path, 'rU').read()pythonbuild_file_contents = open(build_file_path, 'r').read()
Why These Solutions Work
- Python 3.10 supports
rUmode, while 3.11+ does not - New
node-gypversions (v8.0.0+) removedrUusage - Environment variables override hardcoded paths
- Manual source edits bypass deprecated Python syntax
WARNING
Avoid system-wide Python downgrades - use version managers like pyenv for per-project control.
Verifying the Fix
After applying any solution, clear cached builds and retest:
bash
rm -rf node_modules package-lock.json
npm cache clean --force
npm install