Meteor 是建立在 Node.js 之上的全端框架,以「資料即時同步」聞名,極適合構建聊天、協作編輯、即時儀表板等應用。本文手把手教你建立一個完整的即時聊天室,涵蓋專案建立、模板系統、Collection 資料同步、事件處理與部署上線。
# 安裝 Meteor (macOS/Linux)
curl https://install.meteor.com | sh
# 建立專案
meteor create chat
cd chat
# 啟動開發伺服器
meteor
# => Running on: https://localhost:3000/
專案結構:
chat/
├── .meteor/ # Meteor 核心、MongoDB 資料檔 (隱藏)
├── client/ # 客戶端代碼 (瀏覽器執行)
├── server/ # 伺服器代碼 (Node.js 執行)
├── imports/ # 共享模組 (ES6 import/export)
├── public/ # 靜態資源
├── chat.html # 主模板 (舊版單檔結構)
├── chat.css
└── chat.js # 共享邏輯 (舊版)
Meteor 內建 Blaze 模板引擎,語法類似 Mustache/Handlebars。
<head>
<title>Meteor Chat</title>
</head>
<body>
{{> entryField}}
{{> messages}}
</body>
<template name="entryField">
<div class="input-group">
<input type="text" id="messageInput" placeholder="輸入訊息...">
<button id="sendBtn">送出</button>
</div>
</template>
<template name="messages">
<div id="messagesList">
{{#each messages}}
{{> messageItem}}
{{/each}}
</div>
</template>
<template name="messageItem">
<div class="message">
<span class="user">{{username}}:</span>
<span class="text">{{text}}</span>
<span class="time">{{formatTime createdAt}}</span>
</div>
</template>
Meteor 的核心魔力在於 Meteor.Collection:客戶端與伺服器共享同一介面,資料變更自動雙向同步 (DDP 協議)。
// 定義集合,名稱 'messages' 對應 MongoDB 集合
Messages = new Meteor.Collection('messages');
Meteor.isClient 區塊)if (Meteor.isClient) {
// 1. 訂閱發布 (伺服器需對應 Meteor.publish)
Meteor.subscribe('messages');
// 2. 模板輔助:提供 messages 游標給模板
Template.messages.helpers({
messages: function() {
// 依時間倒序,最新在上
return Messages.find({}, { sort: { createdAt: -1 } });
},
formatTime: function(date) {
return moment(date).fromNow(); // 需安裝 moment: meteor npm install moment
}
});
// 3. 事件處理:發送訊息
Template.entryField.events({
'click #sendBtn, keydown #messageInput': function(event, template) {
// Enter 鍵或點擊按鈕觸發
if (event.type === 'keydown' && event.which !== 13) return;
event.preventDefault();
var input = template.find('#messageInput');
var text = input.value.trim();
if (!text) return;
// 插入集合,自動同步到所有連線客戶端
Messages.insert({
text: text,
username: Meteor.user() ? Meteor.user().username : '匿名用戶',
createdAt: new Date()
});
input.value = ''; // 清空輸入框
}
});
// 4. 使用者帳號系統 (內建 accounts-ui + accounts-password)
// 終端機執行: meteor add accounts-ui accounts-password
// 模板中加入 {{> loginButtons}} 即可獲得完整註冊/登入/密碼重設 UI
}
if (Meteor.isServer) {
Meteor.startup(function() {
// 發布訊息集合 (可加入過濾/權限邏輯)
Meteor.publish('messages', function() {
return Messages.find({}, { sort: { createdAt: -1 }, limit: 100 });
});
});
}
Messages.insert 立即在本地渲染,背景同步至伺服器再廣播,零延遲體驗。meteor add ground:db 即可在離線時繼續寫入,上線自動同步。meteor add accounts-ui accounts-password 一鍵獲得完整認證流程。meteor deploy my-chat-app.meteor.com
meteor build ../chat-build --architecture os.linux.x86_64cd bundle/programs/server && npm installMONGO_URL、ROOT_URL、PORTpm2 start main.js --name meteor-chat# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY bundle /app
RUN cd programs/server && npm install --production
ENV MONGO_URL=mongodb://mongo:27017/chat
ENV ROOT_URL=https://chat.example.com
EXPOSE 3000
CMD ["node", "main.js"]
| 特性 | Meteor | Derby.js |
|---|---|---|
| 資料庫 | 深度綁定 MongoDB | 支援多種 (Mongo/PostgreSQL/RethinkDB 等) |
| 同步協議 | DDP (自有) | ShareJS (Operational Transform) |
| 資金/社群 | 1100 萬美元融資、大社群 | 社群較小、文檔較少 |
| 學習曲線 | 平緩、文檔完善 | 較陡峭、概念獨特 |
Meteor 以「資料無處不在」為核心哲學,讓即時應用開發變得前所未有的簡單。雖然綁定 MongoDB 且打包體積較大,但對於快速驗證想法、構建 MVP、中小型即時應用,它是極具競爭力的選擇。