在 Debian 上运行 Node.js,通常分为 安装 Node.js 和 运行 Node 程序 两部分。下面给你几种常见、可靠的做法。
sudo apt update
sudo apt install nodejs npm
检查版本:
node --version
npm --version
适合:学习、简单脚本、对版本要求不高的情况
以 Node.js 20.x 为例:
sudo apt update
sudo apt install -y curl
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
适合:生产环境、现代前端/后端项目
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
node -v
适合:开发机、需要多个 Node 版本
mkdir ~/node-demo
cd ~/node-demo
nano app.js
app.js:
console.log("Hello Debian Node.js");
运行:
node app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Debian!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
运行:
node app.js
访问:
http://<服务器IP>:3000
sudo npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
sudo 跑 npm 全局安装,推荐 nvmlsof -i:3000sudo ufw allow 3000
如果你愿意,可以告诉我:
我可以直接给你一套完整配置。