Ubuntu 22.04使用npm运行NextJS项目时遭遇“sh: 1: next: Exec format error”错误的解决方法咨询
Hey there, sorry to hear you're stuck with this frustrating error! Let's work through some tried-and-true fixes that usually resolve this "Exec format error" issue with Next.js on Ubuntu 22.04:
Check Node.js and npm version compatibility
Next.js has strict Node.js version requirements (for example, Next.js 13+ needs Node.js 16.8 or higher). First, confirm your current versions by running:node -v npm -vIf your Node.js version is too old, using
nvm(Node Version Manager) is the easiest way to manage multiple versions:- Uninstall any old system-wide Node.js and npm first:
sudo apt remove --purge nodejs npm - Install nvm (follow the official setup instructions available in its repository), then install a compatible Node version:
nvm install 20 nvm use 20
This version works with nearly all modern Next.js projects.
- Uninstall any old system-wide Node.js and npm first:
Reinstall dependencies to fix corrupted binaries
The most common culprit here is corrupted or architecture-mismatched binary files in yournode_modulesfolder. Let's wipe and rebuild them from scratch:rm -rf node_modules package-lock.json npm installThis will clean up any broken files and download fresh, Ubuntu-compatible dependencies tailored to your system's architecture.
Use
npxto run the local Next.js binary
Global installations ofnextcan sometimes cause conflicts with project-specific versions. Try running the local version directly with:npx next devnpxwill use the exactnextversion defined in your project'spackage.json, avoiding format mismatches from global installs.Check for architecture mismatches
If you're running Ubuntu on an ARM-based system (like Raspberry Pi or Apple Silicon), you might have accidentally downloaded x86-specific binaries. The fix here is the same as the step above—deletenode_modulesand reinstall, since npm will automatically fetch binaries that match your system's architecture.Verify npm registry configuration
A misconfigured npm registry could lead to downloading corrupted or incompatible packages. Check your current registry settings with:npm config listIf you're using a third-party registry, switch back to the official one and reinstall dependencies:
npm config set registry https://registry.npmjs.org/ rm -rf node_modules package-lock.json npm install
Start with the second step (reinstalling dependencies)—it's the quickest fix for most cases. If that doesn't work, move on to checking your Node.js version.
备注:内容来源于stack exchange,提问作者Madosis

