在 Ubuntu 上运行 Node.js 报错的原因有很多,需要看具体的报错信息才能准确判断。下面我先列出 Ubuntu 上 Node.js 最常见报错及原因,你可以对照看看是哪一种。
command not found: node
或
bash: node: command not found
node -v
如果没版本号:
sudo apt update
sudo apt install nodejs npm
✅ 推荐用 NodeSource 安装新版本:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
SyntaxError: Unexpected token '??'
或
digital envelope routines::unsupported
升级 Node.js(见上面 NodeSource 方法)
EACCES: permission denied
或
npm ERR! code EACCES
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
❌ 不建议长期使用 sudo npm install -g
gyp ERR!
cannot find -lxxx
sudo apt install build-essential
sudo apt install python3
Error: listen EADDRINUSE :::3000
lsof -i:3000
kill -9 <PID>
engine "node" is incompatible
nvm install 18
nvm use 18
请把下面内容贴出来:
node app.js)node -v 和 npm -v 的输出lsb_release -a)我可以直接帮你定位并给出修复命令。