跳至正文

💚 什麼是Node.js?

📖 定義

Node.js是建構在Chrome V8引擎上的JavaScript執行環境。它使JavaScript能夠在瀏覽器外執行,透過非同步事件驅動架構提供高效能和可擴展性。透過npm(Node Package Manager)提供龐大的函式庫生態系統。

🎯 簡單類比

餐廳廚房

傳統伺服器(同步)
└─ 一個廚師按順序服務客戶(慢)

Node.js(非同步)
├─ 一個廚師同時處理多個訂單
├─ 煮牛排時 → 準備沙拉
└─ 快速高效!

⚙️ 事件迴圈

┌─────────────┐
│ Call Stack │ 執行程式碼
└──────┬──────┘

┌──────▼──────┐
│ Event Loop │ 協調器
└──────┬──────┘

┌────┴─────┐
│ │
Microtask Task Queue
(Promise) (setTimeout)

💡 關鍵範例

基本HTTP伺服器

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>你好,Node.js!</h1>');
});

server.listen(3000, () => {
console.log('伺服器執行於 http://localhost:3000');
});

Express API

const express = require('express');
const app = express();

app.use(express.json());

app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: '小明' },
{ id: 2, name: '小華' }
]);
});

app.post('/api/users', (req, res) => {
const newUser = req.body;
res.status(201).json({ message: '建立成功', user: newUser });
});

app.listen(3000);

Async/Await

const fs = require('fs').promises;

// ❌ 順序執行(慢)
async function readSequential() {
const file1 = await fs.readFile('file1.txt');
const file2 = await fs.readFile('file2.txt');
// 總計:200ms
}

// ✅ 並行執行(快)
async function readParallel() {
const [file1, file2] = await Promise.all([
fs.readFile('file1.txt'),
fs.readFile('file2.txt')
]);
// 總計:100ms(並發)
}

資料庫整合

const express = require('express');
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});

app.get('/api/users', async (req, res) => {
try {
const [rows] = await pool.execute('SELECT * FROM users');
res.json(rows);
} catch (error) {
res.status(500).json({ error: '資料庫錯誤' });
}
});

🤔 常見問題

Q1. 為什麼Node.js快?

// 非阻塞I/O
readFile('file.txt', (err, data) => {
processData(data);
});
// 讀取時可以處理其他請求!

// 事件驅動
// 單執行緒處理數千個連線
// 無上下文切換開銷

Q2. 什麼是npm?

# Node.js的套件管理器
npm install express # 安裝套件
npm init -y # 初始化專案
npm list # 列出已安裝的套件
npm audit # 安全檢查

# package.json
{
"dependencies": {
"express": "^4.18.0"
}
}

Q3. CommonJS vs ES模組?

// CommonJS(傳統)
const { add } = require('./math');
module.exports = { add };

// ES模組(現代)
import { add } from './math.js';
export function add(a, b) { return a + b; }

// 在package.json中啟用
{ "type": "module" }

🎬 總結

  • 非同步I/O: 高效能和可擴展性
  • JavaScript: 與前端相同的語言
  • npm: 龐大的套件生態系統
  • 事件迴圈: 高效的並發處理

使用Node.js成為全端開發者! 💚