Node.js 是現在超熱門的後端開發工具,簡單、靈活、超適合做 API、網站後端、即時應用(像聊天室、線上遊戲)等等。
? Node.js 教學入門指南
這份教學會從「什麼是 Node.js」開始,到實際寫一個小小伺服器,幫你快速入門。
? Node.js 是什麼?
Node.js 是一個基於 Chrome V8 引擎的 JavaScript 執行環境,可以讓你用 JavaScript 來寫「後端」程式(例如:伺服器、API、資料庫互動等)。
- ✅ 用 JavaScript 寫後端
- ✅ 非同步 + 事件驅動(很快、適合即時應用)
- ✅ 有超多現成套件(npm)
?️ 安裝 Node.js
- 到 Node.js 官方網站 下載 LTS 版
- 安裝完成後打開終端機(命令提示字元 / Terminal)
- 輸入:
node -v # 看版本
npm -v # npm 是 Node 的套件管理工具
? 第一個 Node.js 程式
- 建一個檔案
app.js - 寫入以下程式碼:
console.log("Hello Node.js!");
- 在終端機執行:
node app.js
? 建立一個簡單的 HTTP 伺服器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, this is a Node.js server!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
執行:
node app.js
→ 打開瀏覽器輸入 http://localhost:3000,你會看到訊息!
? 使用 npm 安裝套件
➤ 安裝 express(超好用的 Web 框架)
npm init -y # 初始化專案
npm install express # 安裝 express
➤ 建立 server.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello Express!');
});
app.listen(3000, () => {
console.log('Express server running at http://localhost:3000');
});
? 常見功能實作範例
| 功能 | 說明 | 工具/套件 |
|---|---|---|
| 路由處理 | /home, /about 等 | Express |
| 靜態檔案 | 提供圖片、HTML、CSS | express.static() |
| 表單接收 | POST 表單資料 | body-parser(已整合進 express) |
| 資料庫連接 | MySQL / MongoDB | mysql2, mongoose |
| REST API | 建立後端接口 | Express |
| 即時聊天 | WebSocket | socket.io |
? 專案架構建議(簡單版)
my-app/
│
├── server.js
├── routes/
│ └── index.js
├── public/
│ └── index.html
├── package.json
└── node_modules/
? 想學什麼方向?
Node.js 可以做很多事,這些是常見選擇?
- ?️ 做 RESTful API(接資料庫、串前端)
- ? 做網站後端(配合前端框架)
- ? 做聊天室(即時通訊)
- ? 寫爬蟲、資料處理
- ? 寫自動化工具 / CLI 工具