萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Meteor + Node.js 實時聊天應用完整教學:從零到部署

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           # 共享邏輯 (舊版)

模板系統:Blaze (Spacebars 語法)

Meteor 內建 Blaze 模板引擎,語法類似 Mustache/Handlebars。

chat.html 完整結構

<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>

資料層:MongoDB Collection 即時同步

Meteor 的核心魔力在於 Meteor.Collection:客戶端與伺服器共享同一介面,資料變更自動雙向同步 (DDP 協議)。

共享定義 (chat.js 或 imports/api/messages.js)

// 定義集合,名稱 'messages' 對應 MongoDB 集合
Messages = new Meteor.Collection('messages');

客戶端邏輯 (client/main.js 或 chat.js 中 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
}

伺服器端邏輯 (server/main.js)

if (Meteor.isServer) {
  Meteor.startup(function() {
    // 發布訊息集合 (可加入過濾/權限邏輯)
    Meteor.publish('messages', function() {
      return Messages.find({}, { sort: { createdAt: -1 }, limit: 100 });
    });
  });
}

關鍵特性體驗

  1. 熱重載:儲存檔案即時刷新瀏覽器,保持應用狀態 (輸入框內容不會清空)。
  2. 樂觀 UI:Messages.insert 立即在本地渲染,背景同步至伺服器再廣播,零延遲體驗。
  3. 離線支援 (Ground:DB):安裝 meteor add ground:db 即可在離線時繼續寫入,上線自動同步。
  4. 帳號系統:meteor add accounts-ui accounts-password 一鍵獲得完整認證流程。

部署上線

方案一:Meteor 免費託管 (適合原型/小專案)

meteor deploy my-chat-app.meteor.com

方案二:自有伺服器 (生產環境推薦)

  1. 建構生產包:meteor build ../chat-build --architecture os.linux.x86_64
  2. 解壓至伺服器,安裝依賴:cd bundle/programs/server && npm install
  3. 設定環境變數:MONGO_URL、ROOT_URL、PORT
  4. 使用 PM2 管理進程:pm2 start main.js --name meteor-chat
  5. 配置 Nginx 反向代理 + SSL。

方案三:Docker 容器化

# 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 vs Derby.js 對比

特性MeteorDerby.js
資料庫深度綁定 MongoDB支援多種 (Mongo/PostgreSQL/RethinkDB 等)
同步協議DDP (自有)ShareJS (Operational Transform)
資金/社群1100 萬美元融資、大社群社群較小、文檔較少
學習曲線平緩、文檔完善較陡峭、概念獨特

Meteor 以「資料無處不在」為核心哲學,讓即時應用開發變得前所未有的簡單。雖然綁定 MongoDB 且打包體積較大,但對於快速驗證想法、構建 MVP、中小型即時應用,它是極具競爭力的選擇。

copyright © 萬盛學電腦網 all rights reserved