温馨提示×

ubuntu下nodejs怎样运行

小樊
47
2026-09-16 00:04:35
栏目: 编程语言

在 Ubuntu 下运行 Node.js,一般按下面步骤来:


一、安装 Node.js

方法 1:使用 apt(简单,版本可能稍旧)

sudo apt update
sudo apt install nodejs npm

检查版本:

node -v
npm -v

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

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

二、运行 Node.js 程序

1️⃣ 直接运行 JS 文件

写一个文件,例如 app.js

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

运行:

node app.js

2️⃣ 进入交互模式(REPL)

node

然后直接输入 JS 代码:

> 1 + 2
3

退出按:

Ctrl + D

.exit

3️⃣ 运行带参数的脚本

node app.js arg1 arg2

在 JS 中通过:

console.log(process.argv);

三、常用命令

命令 作用
node file.js 运行 JS 文件
npm init 初始化项目
npm install 包名 安装依赖
npm run 脚本 运行 package.json 中的脚本

四、示例(HTTP 服务)

const http = require('http');
http.createServer((req, res) => {
  res.end('Hello Ubuntu Node.js');
}).listen(3000);

运行:

node app.js

浏览器访问:

http://localhost:3000

如果你是想 开机自启 / PM2 / Docker / 某个框架(Express、Nest 等),可以告诉我具体需求。

0