温馨提示×

怎样在debian用nodejs

小樊
44
2026-09-01 16:55:34
栏目: 编程语言

在 Debian 上使用 Node.js,通常包含安装、运行、管理版本、简单项目示例几个部分。下面按常见使用方式给你说明。


一、在 Debian 上安装 Node.js

方法 1:使用 Debian 官方源(最简单,但版本可能较旧)

sudo apt update
sudo apt install nodejs npm

查看版本:

node -v
npm -v

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

例如安装 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

方法 3:使用 NVM(适合开发,可切换版本)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
node -v

二、运行 Node.js 程序

1. 写一个简单的 JS 文件

nano hello.js

内容:

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

运行:

node hello.js

2. 启动一个简单的 HTTP 服务

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

三、使用 npm 管理依赖

初始化项目:

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);

四、后台运行 Node.js(生产常用)

使用 PM2

sudo npm install -g pm2
pm2 start server.js
pm2 save
pm2 startup

五、常见问题

1. 权限问题(npm 全局安装报错)

不要用 sudo npm -g,推荐:

npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATH

2. 端口被占用

sudo lsof -i :3000

如果你告诉我你是学习 / 开发 / 服务器部署,我可以给你更具体的 Debian + Node.js 方案。

0