在 Debian 系统上运行 Node.js 脚本,一般流程如下:
sudo apt update
sudo apt install nodejs npm
查看版本:
node -v
npm -v
Debian 稳定版(如 Debian 11/12)自带的 Node.js 版本可能较旧,适合基础使用。
以 Node.js 20.x 为例:
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
重新加载 shell:
source ~/.bashrc
安装 Node.js:
nvm install 20
nvm use 20
mkdir ~/node-test
cd ~/node-test
nano hello.js
内容示例:
console.log("Hello Debian Node.js");
保存并退出。
node hello.js
输出:
Hello Debian Node.js
npm init -y
npm install express
node app.js
nohupnohup node app.js &
systemd(推荐)示例服务文件 /etc/systemd/system/nodeapp.service:
[Unit]
Description=Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /home/user/node-test/app.js
Restart=always
User=user
[Install]
WantedBy=multi-user.target
启动:
sudo systemctl daemon-reexec
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
sudo apt install nodejs
sudo apt install npm
如果你告诉我 Debian 版本 或 使用场景(开发 / 服务器 / Docker),我可以给你更精确的方案。