Live Chat: Implemented using Modulus and Node.js
Sep 03, 2023 pm 11:25 PMIn this tutorial, I will show you how to implement a real-time chat application using Node.js, Socket.IO and MongoDB, and then we will deploy the application together to Modulus.
First, let me show you the final look of the application that we will see at the end of the article.
Node.js will be the core of the application, Express as MVC, MongoDB as database, Socket. IO is used for real-time communication. Once completed, we will deploy the application to Modulus. The MongoDB part actually lives inside Modulus.
1. Scenario
- John wants to use our app and opens it in a browser.
- On the first page, he selects the nickname used during the chat and then logs in to the chat.
- He writes something in the text area and presses Enter.
- The text is sent to a RESTful service (Express) and the text is written to MongoDB.
- The same text will be broadcast to the user currently logged into the chat app before being written in MongoDB.
As you can see, this is a very simple application, but it covers almost everything a web application has to offer. There is no channel system in the application, but you can fork the source code and implement the channel module to practice.
2.Design the project from scratch
I will try to explain the small parts of the project first and then put them together at the end. I'll start with the backend and work my way up to the frontend. So, let's start with the domain objects (MongoDB models).
2.1. model
For database abstraction, we will use Mongoose. In this project, we have only one model named Message
. This message model only contains text
, createDate
, and author
. The author does not have a model like User
, because we will not fully implement the user registration/login system. There will be a simple nickname providing page, and the nickname will be saved to a cookie. This will be used in the Message
model as the text in the author
field. You can see a sample JSON model below:
{ text: "Hi, is there any Full Stack Developer here?" author: "john_the_full_stack", createDate: "2015.05.15" }
To create such a document, you can use the following Mongoose function to implement the model:
var mongoose = require('mongoose') var Message = new mongoose.Schema({ author: String, message: String, createDate: { type: Date, default: Date.now } }); mongoose.model('Message', Message)
Simply import the Mongoose module, define the model with fields and field properties in JSON format, and create a model named Message
. The model will be included in the page you want to use.
Maybe you have questions, why do we store the message in the database when we are already broadcasting this message to the users in the same channel. It's true that you don't have to store chat messages, but I just wanted to explain the database integration layer. Anyway, we will use this model in the controller in our project. Controller?
2.2. Controller
As I said before, we will use Express for the MVC part. And C
here represents Controller
. For our project, there are only two messaging endpoints. One of them is loading recent chat messages and the second one is handling sent chat messages which are stored in database and then broadcast to the channel.
..... app.get('/chat', function(req, res){ res.sendFile(__dirname + '/index.html'); }); app.get('/login', function(req, res){ res.sendFile(__dirname + '/login.html'); }); app.post('/messages', function(req, res, next) { var message = req.body.message; var author = req.body.author; var messageModel = new Message(); messageModel.author = author; messageModel.message = message; messageModel.save(function (err, result) { if (!err) { Message.find({}).sort('-createDate').limit(5).exec(function(err, messages) { io.emit("message", messages); }); res.send("Message Sent!"); } else { res.send("Technical error occurred!"); } }); }); app.get('/messages', function(req, res, next) { Message.find({}).sort('-createDate').limit(5).exec(function(err, messages) { res.json(messages); }); }); .....
The first and second controllers are only used to serve static HTML files for the chat and login pages. The third is used to handle publish requests to the /messages
endpoint to create new messages. In this controller, first convert the request body into a Message model and then use the Mongoose function save
.
I won't delve into Mongoose - you can check out the documentation for more details. You can provide a callback function to the save function to check if there are any problems. If successful, we will get the last 5 records in descending order by createDate
and broadcast 5 messages to the clients in the channel.
Okay, we're done MC
. Let’s switch to the View
section.
2.3. Check
Generally speaking, template engines such as Jade, EJS, and Handlebars can be used in Express. However, we only have one page, and that's a chat message, so I'm going to serve it statically. Actually, as I said above, there are two more controllers serving this static HTML page. You can see the following is used to serve a static HTML page.
app.get('/chat', function(req, res){ res.sendFile(__dirname + '/index.html'); }); app.get('/login', function(req, res){ res.sendFile(__dirname + '/login.html'); });
This endpoint only serves index.html and login.html using res.sendFile
. index.html and login.html are in the same folder as server.js, that's why we use __dirname
before the HTML file name.
2.4。前端
在前端頁面中,我已經(jīng)使用了Bootstrap,無需解釋我是如何做到這一點的。簡單來說,我將一個函數(shù)綁定到一個文本框,每當(dāng)您按下Enter鍵或發(fā)送按鈕時,消息就會發(fā)送到后端服務(wù)。
該頁面還有一個必需的Socket.IO js文件,用于監(jiān)聽名為message
的頻道。 Socket.IO 模塊已在后端導(dǎo)入,當(dāng)您在服務(wù)器端使用此模塊時,它會自動添加一個端點來提供 Socket.IO js 文件,但我們使用由 cdn <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
。每當(dāng)有新消息進入此頻道時,都會自動檢測到該消息,并且消息列表將刷新為最后 5 條消息。
<script> var socket = io(); socket.on("message", function (messages) { refreshMessages(messages); }); function refreshMessages(messages) { $(".media-list").html(""); $.each(messages.reverse(), function(i, message) { $(".media-list").append('<li class="media"><div class="media-body"><div class="media"><div class="media-body">' + message.message + '<br/><small class="text-muted">' + message.author + ' | ' + message.createDate + '</small><hr/></div></div></div></li>'); }); } $(function(){ if (typeof $.cookie("realtime-chat-nickname") === 'undefined') { window.location = "/login" } else { $.get("/messages", function (messages) { refreshMessages(messages) }); $("#sendMessage").on("click", function() { sendMessage() }); $('#messageText').keyup(function(e){ if(e.keyCode == 13) { sendMessage(); } }); } function sendMessage() { $container = $('.media-list'); $container[0].scrollTop = $container[0].scrollHeight; var message = $("#messageText").val(); var author = $.cookie("realtime-chat-nickname"); $.post( "/messages", {message: message, author: author}, function( data ) { $("#messageText").val("") }); $container.animate({ scrollTop: $container[0].scrollHeight }, "slow"); } }) </script>
上面的代碼中還有一項檢查:cookie 部分。如果您沒有選擇任何聊天昵稱,則表示該昵稱沒有設(shè)置cookie,您將自動重定向到登錄頁面。
如果沒有,最后五條消息將通過對 /messages
端點的簡單 Ajax 調(diào)用來獲取。同樣,每當(dāng)您點擊發(fā)送按鈕或按Enter鍵時,都會從文本框中提取短信,并從文本框中提取昵稱。 cookie,這些值將通過 post 請求發(fā)送到服務(wù)器。這里沒有嚴(yán)格檢查昵稱,因為我想關(guān)注實時部分,而不是用戶身份驗證部分。
正如你所看到的,項目的整體結(jié)構(gòu)非常簡單。讓我們進入部署部分。正如我之前所說,我們將使用 Modulus,它是用您選擇的語言部署、擴展和監(jiān)控應(yīng)用程序的最佳 PaaS 之一。
3.部署
3.1。先決條件
我首先想到的是向您展示如何部署,但為了成功部署,我們需要一個工作數(shù)據(jù)庫。我們來看看如何在Modulus上創(chuàng)建數(shù)據(jù)庫,然后進行部署。
創(chuàng)建帳戶后轉(zhuǎn)至 Modulus 儀表板。點擊左側(cè)的數(shù)據(jù)庫菜單,然后點擊創(chuàng)建數(shù)據(jù)庫。
在彈出表單中填寫必填字段,如下所示。
當(dāng)您填寫必填字段并點擊創(chuàng)建時,它將創(chuàng)建一個 MongoDB 數(shù)據(jù)庫您將在屏幕上看到您的數(shù)據(jù)庫 URL。我們將使用 MONGO URI,?因此請復(fù)制該 URI。
在我們的項目中,Mongo URI是從環(huán)境變量MONGO_URI
中獲取的,您需要在儀表板中設(shè)置該環(huán)境變量。轉(zhuǎn)到信息中心,點擊項目菜單,在列表中選擇您的項目,然后點擊左側(cè)菜單中的管理。在此頁面中,向下滾動頁面時您將看到環(huán)境變量部分,如下所示。
您可以通過兩種方式部署到 Modulus:
- 使用儀表板上傳項目 ZIP 文件
- 使用 Modulus CLI 從命令行進行部署
我將繼續(xù)使用命令行選項,因為另一個很容易做到。首先,安裝 Modulus CLI:
npm install -g modulus
轉(zhuǎn)到您的項目文件夾并執(zhí)行以下命令以登錄 Modulus。
modulus login
當(dāng)您執(zhí)行上述命令時,系統(tǒng)會提示您輸入用戶名和密碼:
如果您已使用 GitHub 創(chuàng)建帳戶,則可以使用 --github
選項.
modulus login --github
現(xiàn)在您已登錄 Modulus,可以創(chuàng)建項目了。使用以下命令創(chuàng)建項目:
modulus project create "Realtime Chat"
當(dāng)您運行此函數(shù)時,系統(tǒng)會詢問您運行時。選擇第一個選項,即 Node.js,第二個選項將詢問您伺服器的大小,您可以保留默認(rèn)值。
我們已經(jīng)創(chuàng)建了一個項目,這次我們將把當(dāng)前項目部署到Modulus中。執(zhí)行以下命令將當(dāng)前項目發(fā)送到Modulus端的Realtime Chat項目中。
modulus deploy
它將部署您的項目,并且您將在成功部署消息的末尾獲得正在運行的項目 URL:
Realtime Chat running at realtime-chat-46792.onmodulus.net
如您所見,部署到 Modulus 非常簡單!
The Modulus CLI has very useful commands that can be used during project deployment or runtime. For example, to track the logs of a running project, you can use modulus project log tail
, to create a MongoDB database use modulus mongo create <db-name></db-name>
, and to set environment variables, use modulus env set <key> <value></value></key>
etc. You can use Modulus Help to see the complete list of commands.
in conclusion
The main purpose of this tutorial is to show you how to create a real-time chat application using Node.js, Socket.IO and MongoDB. To run the project in production, Modulus is used as a PaaS provider. The deployment steps for Modulus are very simple, and it also provides an internal database (MongoDB) for our project. Apart from this, you can also use very useful tools like logging, notifications, autoscaling, database management, etc. in the Modulus dashboard.
To sign up for Modulus, click here and get an extra $10 by becoming a Tuts reader. Use promo code ModulusChat10.
For more information about Modulus enterprise products, click here.
The above is the detailed content of Live Chat: Implemented using Modulus and Node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
