温馨提示×

Debian怎样运行Nodejs脚本

小樊
45
2026-07-01 19:45:59
栏目: 编程语言

Debian 系统上运行 Node.js 脚本,一般流程如下:


一、安装 Node.js

✅ 方法一:使用 Debian 官方源(稳定但版本可能较旧)

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v
npm -v

Debian 稳定版(如 Debian 11/12)自带的 Node.js 版本可能较旧,适合基础使用。


✅ 方法二:使用 NodeSource(推荐,版本新)

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

✅ 方法三:使用 NVM(适合开发环境)

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

二、创建并运行 Node.js 脚本

1️⃣ 创建脚本文件

mkdir ~/node-test
cd ~/node-test
nano hello.js

内容示例:

console.log("Hello Debian Node.js");

保存并退出。


2️⃣ 运行脚本

node hello.js

输出:

Hello Debian Node.js

三、使用 npm 管理项目(可选)

初始化项目

npm init -y

安装依赖

npm install express

运行带依赖的脚本

node app.js

四、后台运行 Node.js(生产环境)

使用 nohup

nohup 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

五、常见问题

❓ node 命令不存在

sudo apt install nodejs

❓ npm 不存在

sudo apt install npm

如果你告诉我 Debian 版本使用场景(开发 / 服务器 / Docker),我可以给你更精确的方案。

0