在 Debian 上使用 Node.js,通常包含安装、运行、管理版本、简单项目示例几个部分。下面按常见使用方式给你说明。
sudo apt update
sudo apt install nodejs npm
查看版本:
node -v
npm -v
例如安装 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
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
node -v
nano hello.js
内容:
console.log("Hello Debian Node.js");
运行:
node hello.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js on Debian\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
运行:
node server.js
浏览器访问:
http://localhost:3000
初始化项目:
mkdir myproject && cd myproject
npm init -y
安装依赖示例:
npm install express
使用:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Express on Debian');
});
app.listen(3000);
sudo npm install -g pm2
pm2 start server.js
pm2 save
pm2 startup
不要用 sudo npm -g,推荐:
npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATH
sudo lsof -i :3000
如果你告诉我你是学习 / 开发 / 服务器部署,我可以给你更具体的 Debian + Node.js 方案。