Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Ubuntu 系統運行 Node.js Hello World 入門實戰

編輯:關於 Linux

Node.js 以事件驅動、非阻塞 I/O 模型著稱,是構建高併發 Web 服務的首選。本文從安裝 Node.js 到運行控制台版與 HTTP 服務器版 Hello World,帶您跨入 Node.js 開發大門。

Node.js Hello World 運行截圖

步驟 1:安裝 Node.js(推薦使用 NVM 管理版本)

# 安裝 NVM (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc

# 安裝長期支持版 (LTS)
nvm install --lts
# 或指定版本
# nvm install 20.11.0

# 驗證
node -v   # v20.11.0
npm -v    # 10.2.4

備選:apt install nodejs npm(版本較舊)、官網下載二進制包、Docker 運行。

步驟 2:控制台版 Hello World

創建 helloworld.js:

console.log('Hello World!');

運行:

node helloworld.js
# 輸出:Hello World!

步驟 3:HTTP 服務器版 Hello World(Web 入門)

修改 helloworld.js:

const http = require('http');

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

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at https://localhost:${PORT}/`);
});

運行:

node helloworld.js
# 輸出:Server running at https://localhost:3000/

瀏覽器訪問 https://localhost:3000/ 或 curl https://localhost:3000/,顯示 Hello World!。

核心代碼解析

代碼含義
require('http')引入內建 http 模組
http.createServer(callback)創建 HTTP 服務器,回調處理每個請求
req請求對象(IncomingMessage),含 headers、url、method、body 流
res響應對象(ServerResponse),用於寫入頭、體、結束響應
res.writeHead(200, {...})發送狀態碼 200 及響應頭
res.end(data)發送響應體並結束響應
server.listen(port, callback)綁定端口監聽連接,回調在服務器啟動後執行

進階:使用 Express 框架簡化開發

# 安裝 Express
npm init -y
npm install express

# app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World from Express!');
});

app.listen(3000, () => console.log('Express on :3000'));

運行 node app.js,體驗路由、中間件、模板引擎等豐富生態。

開發效率工具:nodemon 熱重載

npm install -g nodemon
# 或 npx nodemon
nodemon helloworld.js
# 修改代碼保存後自動重啟,無需手動 Ctrl+C + 重新運行

常見問題排查

現象原因解決
Error: listen EADDRINUSE端口被佔用lsof -i :3000 找到進程 kill,或換端口
Cannot find module模塊未安裝或路徑錯誤npm install、檢查 node_modules、相對路徑以 ./ 開頭
中文亂碼響應頭缺 charsetres.setHeader('Content-Type', 'text/plain; charset=utf-8')
npm 安裝極慢默認源在國外npm config set registry https://registry.npmmirror.com

下一步學習路徑

  1. 掌握 非同步編程:Promise、async/await、Event Loop。
  2. 學習 Express/Koa/NestJS 框架構建 RESTful API。
  3. 連接 數據庫:MongoDB (Mongoose)、PostgreSQL (Prisma/TypeORM)、Redis (ioredis)。
  4. 掌握 認證授權:JWT、OAuth2、Session/Cookie。
  5. 學習 測試:Jest、Supertest、Cypress。
  6. 容器化部署:Dockerfile、docker-compose.yml、Kubernetes。

從一行 console.log 到高併發微服務,Node.js 之旅始於 Hello World。動手敲代碼,比看一百遍教程更有效!

Copyright © Windows教程網 All Rights Reserved