温馨提示×

怎么在Ubuntu运行Nodejs

小樊
33
2026-08-21 19:01:05
栏目: 编程语言

在 Ubuntu 上运行 Node.js,一般按下面步骤来即可(从安装到运行你的第一个程序):


一、安装 Node.js

✅ 方法一:使用 Ubuntu 官方仓库(最简单,但版本可能较旧)

sudo apt update
sudo apt install nodejs npm

检查版本:

node -v
npm -v

✅ 方法二(推荐):使用 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(Node Version Manager)

1️⃣ 安装 nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

然后执行:

source ~/.bashrc

(如果是 zsh,执行 source ~/.zshrc

2️⃣ 安装 Node.js

nvm install 20
nvm use 20

验证:

node -v
npm -v

二、运行 Node.js 程序

1️⃣ 创建一个测试文件

mkdir test-node
cd test-node
nano app.js

写入内容:

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

保存并退出(Ctrl + O → Enter → Ctrl + X)


2️⃣ 运行 Node.js

node app.js

输出:

Hello Node.js!

三、运行一个简单的 HTTP 服务(可选)

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js server!\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:

node app.js

浏览器访问:

http://localhost:3000

四、常用命令速查

node file.js        # 运行 JS 文件
node                # 进入 Node REPL
npm init            # 初始化项目
npm install express # 安装依赖

如果你告诉我:

  • Ubuntu 版本(如 20.04 / 22.04)
  • 是服务器还是本地开发
  • 是否要部署网站 / API / 前端项目

我可以给你更精确的配置方案 ✅

0