
במדריך זה נשתמש בפלטפורמת Node.js לבניית יישום צ'אט בזמן אמת השולח ומציג הודעות לנמען באופן מיידי ללא כל רענון עמוד. נשתמש במסגרת JavaScript Express.js ובספריות Mongoose ו- Socket.io כדי להשיג זאת.
לפני שנתחיל, נסתכל במהירות על היסודות של Node.js
Node.js
Node.js היא סביבת זמן ריצה של קוד פתוח, חוצה פלטפורמות, שמבצעת קוד JavaScript מחוץ לדפדפן. היתרון החשוב ביותר בשימוש ב- Node הוא שאנחנו יכולים להשתמש ב- JavaScript כשפה חזיתית וגם back-end.
כידוע, JavaScript שימש בעיקר לסקריפטים בצד הלקוח, בהם סקריפטים הוטמעו ב- HTML של דף אינטרנט ומופעלים בצד הלקוח על ידי מנוע JavaScript בדפדפן האינטרנט של המשתמש.
Node.js מאפשר למפתחים להשתמש ב- JavaScript בכדי לכתוב כלים בשורת הפקודה ולתסריטים בצד השרת - הפעלת סקריפטים בצד השרת כדי לייצר תוכן דף דינמי לפני שהדף נשלח לדפדפן האינטרנט של המשתמש.
להתקנת צומת:
//nodejs.org/en/download/
למרות שהצומת מושחל בודד, עדיין מהיר יותר להשתמש בפונקציות אסינכרוניות. לדוגמא, צומת יכול לעבד דברים אחרים בזמן קריאת הקובץ מהדיסק, או בזמן שהוא ממתין להשלמת בקשת HTTP. ניתן ליישם את ההתנהגות האסינכרונית באמצעות התקשרות חוזרות. כמו כן ה- JavaScript עובד היטב עם מסדי נתונים JSON ו- No-SQL.
מודולי NPM
Nodejs מאפשר לכלול את המודולים של הספריות ביישום. מודולים אלה יכולים להיות מוגדרים על ידי המשתמש או מודולים של צד שלישי.
ניתן להתקין את המודולים של הצד השלישי באמצעות הפקודה הבאה:
npm install module_name
וניתן להשתמש במודולים המותקנים באמצעות פונקציית הדרישה () :
var module = require(‘module_name’)
באפליקציות של צומת נשתמש בקובץ package.json לשמירה על גרסאות המודול. ניתן ליצור קובץ זה באמצעות פקודה זו:
npm init
ויש להתקין את החבילות באופן הבא:
npm install -s module_name
ישנן מסגרות רבות שניתן להוסיף כמודולים ליישום הצומת שלנו. אלה יוסברו בהמשך לפי הצורך.
יישום צ'אט פשוט
על האפליקציה לאפשר למספר משתמשים לשוחח בצ'אט יחד. יש לעדכן את ההודעות מבלי לרענן את הדף. למען הפשטות נימנע מחלק האימות.
אנו יכולים להתחיל ביצירת ספריית פרויקטים חדשה ועוברים אליה. אז נוכל ליזום את הפרויקט שלנו לפי הפקודה הבאה:
npm init
זה ידרבן אותנו להזין פרטים על הפרויקט שלנו.
לאחר מכן ייווצר קובץ package.json :
{ “name”: “test”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1" }, “author”: “”, “license”: “ISC” }
ספריית האפליקציות שלנו מוגדרת כעת.
הדבר הראשון שעלינו ליצור הוא שרת. על מנת ליצור זאת, נשתמש במסגרת בשם אקספרס.
Express.js
Express.js, או פשוט Express, היא מסגרת ליישומי אינטרנט עבור Node.js. אקספרס מספק קבוצה חזקה של תכונות ליישומי אינטרנט ומובייל. Express מספק שכבה דקה של תכונות בסיסיות של יישומי אינטרנט, מבלי לטשטש את תכונות Node.js.
אנו נתקין את Express.js באמצעות הפקודה הבאה:
npm install -s express
בתוך קובץ package.json תתווסף שורה חדשה:
dependencies”: { “express”: “⁴.16.3” }
בשלב הבא ניצור קובץ server.js .
בקובץ זה עלינו לדרוש אקספרס וליצור הפניה למשתנה ממופע של אקספרס. ניתן להגיש תכנים סטטיים כמו HTML, CSS או JavaScript באמצעות express.js:
var express = require(‘express’); var app = express();
ונוכל להתחיל להקשיב ליציאה באמצעות הקוד:
var server = app.listen(3000, () => { console.log(‘server is running on port’, server.address().port); });
כעת עלינו ליצור קובץ HTML index.html המציג את ממשק המשתמש שלנו. הוספתי bootstrap ו- JQuery cdn.
//index.html
Send Message
Send
שימו לב שהתג הריק < ; / script> יהיה המקום בו נכתוב את קוד ה- JavaScript בצד הלקוח.
על מנת לומר לאקספרס זאת, נשתמש בקובץ סטטי. נוסיף שורה חדשה בתוך server.js:
app.use(express.static(__dirname));
אנו יכולים להריץ את server.js באמצעות הפקודה
node ./server.js
או חבילה בשם nodemon , כך שהשינויים שבוצעו בקוד יזוהו אוטומטית. אנו נוריד את nodemon באמצעות הפקודה
npm install -g nodemon
-g - גלובלי, כך שיהיה נגיש בכל הפרויקטים.
נפעיל את הקוד באמצעות הפקודה
nodemon ./server.js
אם אתה הולך ל- localhost: 3000 אנו יכולים לראות את קובץ האינדקס:

כעת, כאשר השרת שלנו פועל, עלינו ליצור את מסד הנתונים שלנו. עבור יישום זה יהיה לנו מסד נתונים ללא SQL ונשתמש ב- Mongodb . אני מגדיר את המונגודב שלי ב- mlab.com . מאגר המידע שלנו יכיל אוסף יחיד הנקרא הודעות עם שדות שם ואת ההודעה.

על מנת לחבר בסיס נתונים זה לאפליקציה, נשתמש בחבילה אחרת בשם Mongoose .
נְמִיָה
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose can be installed using the command
npm install -s mongoose
Inside server.js we will require mongoose:
var mongoose = require(‘mongoose’);
And we will assign a variable, the URL of our mlab database:
var dbUrl = ‘mongodb://username:[email protected]:57981/simple-chat’
Mongoose will connect to the mlab database with the connect method:
mongoose.connect(dbUrl , (err) => { console.log(‘mongodb connected’,err); })
And we will be defining our message model as
var Message = mongoose.model(‘Message’,{ name : String, message : String})
We can implement the chat logic now. But before that there is one more package that needs to be added.
Body-Parser
Body-Parser extracts the entire body portion of an incoming request stream and exposes it on req.body. The middleware was a part of Express.js earlier, but now you have to install it separately.
Install it using the following command:
npm install -s body-parser
Add the following codes to server.js:
var bodyParser = require(‘body-parser’) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false}))
Routing
Routing refers to how an application’s endpoints (URIs) respond to client requests. You define routing using methods of the Express app object that correspond to HTTP methods: app.get() to handle GET requests and app.post() to handle POST requests.
These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified routes and methods, and when it detects a match, it calls the specified callback function.
Now we need to create two routes to the messages for our chat to work.
Inside server.js:
get : will get all the message from database
app.get('/messages', (req, res) => { Message.find({},(err, messages)=> { res.send(messages); }) })
post : will post new messages created by the user to the database
app.post('/messages', (req, res) => { var message = new Message(req.body); message.save((err) =>{ if(err) sendStatus(500); res.sendStatus(200); }) })
In order to connect these routes to the front end we need to add the following code in the client side script tag in the index.html:
$(() => { $("#send").click(()=>{ sendMessage({ name: $("#name").val(), message:$("#message").val()}); }) getMessages() }) function addMessages(message){ $(“#messages”).append(` ${message.name}
${message.message}
`) } function getMessages(){ $.get(‘//localhost:3000/messages', (data) => { data.forEach(addMessages); }) } function sendMessage(message){ $.post(‘//localhost:3000/messages', message) }
Here the sendMessage is used to invoke the post route of the messages, and save a message sent by the user. The message is created when a user clicks the send button.
Similarly the getMessage is used to invoke the get route of messages. This will get all the messages saved in the database and will be appended to the messages div.

The only issue now is that there is no way for the client to know if the server is updated. So each time we post a message we need to refresh the page to see the new messages.
To solve this we can add a push notification system that will send messages from server to client. In Node.js we use socket.io.
Socket.io
Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and server. It has two parts: a client-side library that runs in the browser, and a server-side library for Node.js. Socket.io enables real-time bidirectional event-based communication.
To install socket.io:
npm install -s socket.io
we also need an HTTP package for Socket.io to work:
npm install -s http
Add the following code to server.js:
var http = require(‘http’).Server(app); var io = require(‘socket.io’)(http);
And we can create a connection:
io.on(‘connection’, () =>{ console.log(‘a user is connected’) })
In the index.html add the following tag:
Now we need to create an emit action when a message is created in server.js. So the post route becomes this:
app.post('/messages', (req, res) => { var message = new Message(req.body); message.save((err) =>{ if(err) sendStatus(500); io.emit('message', req.body); res.sendStatus(200); }) })
And in the client side script tag in index.html, add the following code:
var socket = io(); socket.on(‘message’, addMessages)
So each time a message is posted, the server will update the messages in the message div.

Great!!
This is very basic application that we can create in Node.js. There is lot of scope for improvement. The finished code can be found in //github.com/amkurian/simple-chat
server.js
var express = require('express'); var bodyParser = require('body-parser') var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var mongoose = require('mongoose'); app.use(express.static(__dirname)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})) var Message = mongoose.model('Message',{ name : String, message : String }) var dbUrl = 'mongodb://username:[email protected]:57981/simple-chat' app.get('/messages', (req, res) => { Message.find({},(err, messages)=> { res.send(messages); }) }) app.get('/messages', (req, res) => { Message.find({},(err, messages)=> { res.send(messages); }) }) app.post('/messages', (req, res) => { var message = new Message(req.body); message.save((err) =>{ if(err) sendStatus(500); io.emit('message', req.body); res.sendStatus(200); }) }) io.on('connection', () =>{ console.log('a user is connected') }) mongoose.connect(dbUrl ,{useMongoClient : true} ,(err) => { console.log('mongodb connected',err); }) var server = http.listen(3001, () => { console.log('server is running on port', server.address().port); });
Hope this was helpful in understanding some basic concepts.
Some useful links
Socket.IO
SOCKET.IO 2.0 IS HERE FEATURING THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE ~/Projects/tweets/index.js var io =…socket.ioExpress - Node.js web application framework
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and…expressjs.com
//mongoosejs.com/