在 Ubuntu 上运行 Node.js,一般按下面步骤来即可(从安装到运行你的第一个程序):
sudo apt update
sudo apt install nodejs npm
检查版本:
node -v
npm -v
以 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
然后执行:
source ~/.bashrc
(如果是 zsh,执行 source ~/.zshrc)
nvm install 20
nvm use 20
验证:
node -v
npm -v
mkdir test-node
cd test-node
nano app.js
写入内容:
console.log("Hello Node.js!");
保存并退出(Ctrl + O → Enter → Ctrl + X)
node app.js
输出:
Hello Node.js!
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 # 安装依赖
如果你告诉我:
我可以给你更精确的配置方案 ✅