Advanced Node and Express Flashcards

1
Q

What is a template engine?

A

software tool that simplifies the process of generating dynamic content for web applications. It allows developers to create templates, which are essentially static HTML files with embedded placeholders for dynamic content. These placeholders can be replaced with actual data during runtime, enabling the creation of web pages that can adapt to different data sources or user inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What the first step in setting up a template engine?

A

npm install ‘template package’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

After installing the template engine, in your Express application, how would you configure it to use the template engine as the view engine?

A

// Set EJS as the view engine
app.set(‘view engine’, ‘ejs’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

After setting the view engine, how do you set the directory for your views?

A

app.set(‘views’, ‘views’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Where do you create template engine files?

A

in the directory specified by ‘app.set(‘views’, ‘views’), depending where you’ve set it to look in ex. views, create a file it that directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

After creating the views, where and how do you render the views?

A

-inside the route handlers
-by using the res.render()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is res.render()

A

method in Express is used to render a view/template and send the rendered HTML to the client in response to an HTTP request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the syntax for res.render()?
and explain what each part does:

A

res.render(view, locals, callback)
-views= name of the view/template file to render
-locals= object containing local variables that will be passed to the view for rendering
-callback= callback function that will be called ionce the view rendering is complete

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Show an ex. on using res.render() for a ‘hello.ejs’ view, and also containing local variable ‘name’ being ‘John’:

A

app.get(‘/hello’, (req, res) => {
// Render the ‘hello.ejs’ view
res.render(‘hello’, { name: ‘John’ });
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is passport.js?

A

is a popular authentication middleware for Node.js applications ,that supports various authentication strategies, such as username and password, OAuth, and OpenID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What various authentication strategies does passport.js support?

A

username and password, OAuth, and OpenID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the main passport.js module?

A

passport

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is passport.js strategy for authenticating with a username and password?

A

passport-local

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is express middleware formanaging sessions?

A

express-session

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is library for hashing passwords securely?

A

bcrypt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is passport?

A

an authentication middleware for Node.js. It is designed to serve a singular purpose—authenticate requests—and it does so in a modular way that allows you to apply different authentication mechanisms, known as strategies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is passport-local?

A

a module that implements a local authentication strategy for Passport. The “local” part means that it uses a username (or email) and password for authentication.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is express-session?

A

middleware for Express that handles sessions. It provides session management capabilities and is essential for maintaining a persistent state across multiple pages, which is useful for keeping a user logged in as they navigate your application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is bcrypt?

A

a library used to hash passwords. bcrypt provides a way to safely store and compare hashed passwords.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you configure express-session middleware?

A

app.use(session({
secret: process.env.SESSION_SECRET, // Change this to a random string
resave: false,
saveUninitialized: false
}));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you inialize passportand session support?

A

app.use(passport.initialize());
app.use(passport.session());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Show a middleware for parsing incoming bodies:

A

app.use(express.urlencoded({ extended: true }));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is serialization of a user object?

A

is an essential aspect of authentication systems, particularly in web applications. It involves converting a user object into a format suitable for storage or transmission, typically for the purpose of session management.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is often used to store user information in a session after successful authentication and retrieves it on a subsequent requests to identify the authenticated user?

A

serialization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Explain how serialization typically works in such systems:

A

After a user is authenticated, their user object is serialized. This typically involves extracting a unique identifier (such as the user’s ID) from the user object and storing it in the session. The serialized user object is then stored in the session store (e.g., memory, database).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Explain how deserialization typically wrks in such systems:

A

On subsequent requests, the session middleware retrieves the serialized user object from the session store using the unique identifier stored during serialization. This serialized user object is then deserialized, typically by fetching the complete user object from the database based on the unique identifier.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What happens to the complete user object once it is deserialized?

A

its attached to the request object (often as req.user)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Show an example on how you would serialize the user object:

A

passport.serializeUser((user, done) => {
done(null, user.id); // Serialize by user ID
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Show an exaple on how you would deserialize the user object:

A

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user); // Deserialize by fetching user from database
});
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does passport.serializeUser do?

A

serializes the user object by extracting and storing its ID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What does passport.deserializeUser do?

A

deserializes the user object by fetching the complete user object from the database using the stored ID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What methods do you need to ensure that your model contains, when using the serialization and deserialization process?

A

methods for finding users by ID (findById) and validating passwords (validPassword)

33
Q

To ensure that your ‘Model’ contains methods for finding users by ID and validating passwords, whats one thing you can do?

A

define these methods within your “Model”

34
Q

To ensure that your ‘Model’ contains methods for finding users by ID and validating passwords, show an example on how it would look like using mongoose:

A

const mongoose = require(‘mongoose’);
const bcrypt = require(‘bcrypt’);
const Schema = mongoose.Schema;

// Define the user schema
const userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
});

// Method to validate a password
userSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

// Export the User model
const User = mongoose.model(‘User’, userSchema);

module.exports = User;

35
Q

What is a way for authenticating a user?

A

strategies

36
Q

Set up local strategy for passport by requiring the strategy and defining a new instance of local strateghy where you specify the authentication logic:

A

const passport = require(‘passport’);
const LocalStrategy = require(‘passport-local’).Strategy;

passport.use(new LocalStrategy(
(username, password, done) => {
myDataBase.findOne({ username: username }, (err, user) => {
console.log(User ${username} attempted to log in.);
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: ‘Incorrect username.’ });
}
// Use the validPassword method we defined in the userSchema to check the password
if (!user.validPassword(password)) {
return done(null, false, { message: ‘Incorrect password.’ });
}
return done(null, user);
});
}
));

37
Q

To set up routes that will use the Passport strategy to authenticate users, create an endpoint that handle login requests and utilize Passports’s authenticate method:

A

const express = require(‘express’);
const router = express.Router();

// Assuming you’re using express
router.post(‘/login’, passport.authenticate(‘local’, {
successRedirect: ‘/dashboard’, // redirect to the secure dashboard section
failureRedirect: ‘/login’, // redirect back to the login page if there is an error
failureFlash: true // allow flash messages
}));

module.exports = router;

38
Q

After setting up routes using Passport Strategies to authenticate users, show how you would use that route in your app.js/server.js:

A

const express = require(‘express’);
const session = require(‘express-session’);
const passport = require(‘passport’);
const authRoutes = require(‘./routes/authRoutes’); // Assuming your authentication routes are defined in a separate file
const app = express();

// Initialize session and passport middleware
app.use(session({ secret: ‘someSecret’, resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Mount the authentication routes at a specific path
app.use(‘/auth’, authRoutes);

// Other middleware and route handlers…
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

39
Q

Create a middleware that checks if a user is authenticated before allowing access to certain routes:

A

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { //checks if current user session is authenticated
return next();
}
res.redirect(‘/login’); //redirection occurs if not authenticated
}

40
Q

After creating a secure route middleware that checks if user is authentcated, show how you can use that on routes you want to protect:

A

app.get(‘/dashboard’, ensureAuthenticated, (req, res) => {
res.render(‘dashboard’, { user: req.user });
});

41
Q

Show how to render the profile view with the user’s username in the route handler for the profile page

A

app.get(‘/profile’, ensureAuthenticated, (req, res) => {
// Render the profile view and pass the user’s username
res.render(‘profile’, { username: req.user.username });
});

42
Q

What do you typically need to implement to log a user out using Passport.js?

A

need to provide a route that handles the logout operation

43
Q

Show how to implement logging a user out using Passport.js:

A

// Route for logging out
app.get(‘/logout’, (req, res) => {
req.logout(); // Passport.js provides a logout() method on the request object to clear the login session
res.redirect(‘/login’); // Redirect to the login page after logout
});

44
Q

What method provided by Passport.js is used to clear the login session and effectively log the user out?

A

req.logout()

45
Q

What redirects the user to the login page after they have been logged out?

A

res.redirect(‘/login)

46
Q

Create a error handler middleware, for missing pages (404), that catches any errors that occur during the request processing pipeline, sets the appropriate status code, and sends a simple ‘error’ message back to the client:

A

// Catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error(‘Not Found’);
err.status = 404;
next(err);
});

// Error handler
app.use((err, req, res, next) => {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};
// Render the error page
res.status(err.status || 500);
// For simplicity, sending text, but you could render a view
if (err.status === 404) {
res.send(‘404: Page Not Found’);
} else {
res.send(‘error’);
}
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

47
Q

Implement registration of a new user with MongoDB in your express application making sure the folllowing is also included:
1. Set up MongoDB connection
2. Create user schema
3. Handle registration POST request

A

const express = require(‘express’);
const bcrypt = require(‘bcrypt’);
const mongoose = require(‘mongoose’);
const app = express();

// Connect to MongoDB
mongoose.connect(‘mongodb://localhost:27017/myapp’, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});

// Define User Schema
const userSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true }
});
const User = mongoose.model(‘User’, userSchema);

// Set up body parser middleware to parse form data
app.use(express.urlencoded({ extended: true }));

// Registration form route (GET)
app.get(‘/register’, (req, res) => {
res.render(‘register’); // Assuming your EJS file is named register.ejs
});

// Registration route (POST)
app.post(‘/register’, async (req, res) => {
const { username, email, password } = req.body;
try {
// Check if user already exists
const existingUser = await User.findOne({ $or: [{ username }, { email }] });
if (existingUser) {
return res.status(400).send(‘Username or email already exists’);
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create new user
const newUser = new User({
username,
email,
password: hashedPassword
});
// Save user to the database
await newUser.save();
// Redirect to login page
res.redirect(‘/login’);
} catch (error) {
console.error(error);
res.status(500).send(‘Internal Server Error’);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

48
Q

What is one thing you can do to enhance security, when working with user authentication?

A

hash passwords

49
Q

What are two key areas you should handle hashing passwords?

A

-registration /saving a new account
-when verifying passwords during login

50
Q

When auser registers and creates a new account, you should hash their password before storing it in the database. Show how you can do this:

A

const bcrypt = require(‘bcrypt’);

// Assume req.body contains username, email, and password from the registration form
// Hash password before saving user data
bcrypt.hash(req.body.password, 10, (err, hashedPassword) => {
if (err) {
// Handle error
} else {
// Save user data to the database, including hashedPassword
User.create({
username: req.body.username,
email: req.body.email,
password: hashedPassword
}, (err, newUser) => {
if (err) {
// Handle error
} else {
// User registered successfully
res.redirect(‘/login’);
}
});
}
});

51
Q

When a user attempts to login, you should compare the provided password stored in the database. Show how you can do this:

A

// Assume req.body contains username/email and password from the login form

User.findOne({ username: req.body.username }, (err, user) => {
if (err) {
// Handle error
} else if (!user) {
// User not found
// Handle accordingly (e.g., show error message)
} else {
// Compare provided password with hashed password in the database
bcrypt.compare(req.body.password, user.password, (err, result) => {
if (err) {
// Handle error
} else if (result === true) {
// Passwords match, user authenticated
// Redirect to authenticated route or set session
res.redirect(‘/dashboard’);
} else {
// Passwords don’t match
// Handle accordingly (e.g., show error message)
}
});
}
});

52
Q

What function can you use to hash passwords before saving it?

A

bcrypt.hash()

53
Q

What function can you use to verify the password during login?

A

bcrypt.compare()

54
Q

To implement password hashing in your authentication straegy, where whould you integrate it into?

A

strategy’s logic

55
Q

Show how you can modify the LocalStrategy authentication strategy to handle password hashing:

A

const LocalStrategy = require(‘passport-local’).Strategy;
const bcrypt = require(‘bcrypt’);

// Assuming User model is imported and available
passport.use(new LocalStrategy(
(username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: ‘Incorrect username.’ }); }
// Compare provided password with hashed password in the database
bcrypt.compare(password, user.password, (err, result) => {
if (err) { return done(err); }
if (result) {
return done(null, user);
} else {
return done(null, false, { message: ‘Incorrect password.’ });
}
});
});
}
));

56
Q

In Chat Intregation, when setting up the enviroment, how can you handle listening for a new connection from the client?

A

By using the on keyword. which listens for a specific event

57
Q

In chat intregation, what does the on keyword require?

A

requires 2 arguments: a string containing the title of the event that’s being emitted, and a function with which the data is passed through.

58
Q

What is a socket?

A

is an individual client who is connected

59
Q

In chat intregation, what would the server.js file look like when setting up the enviroment?
Hint:
//Create an Express app
//Create an HTTP server instance usinghttp.createServer()
//Initialize Socket.IO to work with the HTTP server instance
//Define the port number
//Start listening on the defined port
//Database initialization and route setup:
(//Pass Express app and datbase instance to the routes setup function
//Listen or socket connectons)

A

const express = require(‘express’);
const http = require(‘http’);
const socketIo = require(‘socket.io’);
const routes = require(‘./Routes’);

// Create an Express app
const app = express();

// Create an HTTP server instance using http.createServer()/This servercan then listen for imcoming HTTP requests and route them to the appropiate handlers within app for processing and response
const httpServer = http.createServer(app);

// Initialize Socket.IO to work with the HTTP server instance/Allowing biderectional communication b/w the server & connected clients using Websockets
const io = socketIo(httpServer);

// Define the port number
const PORT = process.env.PORT || 3000;

// Start listening on the defined port
httpServer.listen(PORT, () => {
console.log(Listening on port ${PORT});
});

// Database initialization and route setup
myDB(async client => {
const myDataBase = await client.db(‘database’).collection(‘users’);

// Pass Express app and database instance to the routes setup function
routes(app, myDataBase);

// Listen for socket connections
io.on('connection', socket => {
    console.log('A user has connected');
}); });
60
Q

In chat intregation, what would the routes.js file look like when setting up the enviroment?
HInt:
//Export a function that sets up application routes
(//Define routes using Express
//route initiates the authentication process)

A

const passport = require(‘passport’);

// Export a function that sets up application routes
module.exports = (app, myDataBase) => {
// Define routes using Express
//route inities the authentication process
app.route(‘/auth/github’).get(passport.authenticate(‘github’));

//Route handles the callback from Github and completes the authentication process
app.route('/auth/github/callback')
    .get(passport.authenticate('github', { failureRedirect: '/' }), (req, res) => {
        req.session.user_id = req.user.id;
        res.redirect('/chat');
    }); };
61
Q

In chat intregation, what would the client.js file look like when setting up the enviroment?
Hint:
//Establish WebSocket connection with the server
//Submit form handler
(//Prevent form submit from refreshing page)

A

$(document).ready(function () {
// Establish WebSocket connection with the server
let socket = io();

// Submit form handler
$('form').submit(function () {
    var messageToSend = $('#m').val();
    $('#m').val('');
    return false; // prevent form submit from refreshing page
}); });
62
Q

In chat intregation, what does the server-side do?

A

handles HTTP requests, WebSocket connections, and database operations

63
Q

In chat intregation, what does the client-side do?

A

establishes a WebSocket connection and handles user interactions

64
Q

In Socket.IO, what does communication by emitting refers to?

A

the process of sending data between the server and the connected clients

65
Q

What is a fundamental mechanism for real-time bidirectional commmunication in Socket.IO?

A

communication by emitting

66
Q

In Socket.IO, what are a few reasons for the purpose of emitting?

A

Real-time Communication
DataTransfer
Event-Driven Architecture

67
Q

What would the Server-side code look like for emitting the current count of connected users?

A

const express = require(‘express’);
const http = require(‘http’);
const socketIo = require(‘socket.io’);

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

let connectedUsersCount = 0;

io.on(‘connection’, socket => {
// Increment the count of connected users when a new user connects
connectedUsersCount++;

// Emit the updated count of connected users to all clients
io.emit('userCount', connectedUsersCount);

// Log the current count of connected users
console.log(`A user has connected. Total users: ${connectedUsersCount}`); });

server.listen(3000, () => {
console.log(‘Server running on port 3000’);
});

68
Q

What would the Client-side code look like for emitting the current count of connected users?

A

// Client-side code
socket.on(‘userCount’, count => {
console.log(‘Number of connected users:’, count);
});

69
Q

In Socket.IO for chat intregation, how do you implement Handle a Disconnect on the Server-side code?
Hint:
//Increment count of connected users
//Emit the updated count to all connected sockets
//Log a message indicating a new user connection
//Handle disconnection
(//Decrement count of connected users
//Emit the updated count to all connected sockets
//Log a message indicating a user disconnection)

A

const express = require(‘express’);
const http = require(‘http’);
const socketIo = require(‘socket.io’);
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

let connectedUsersCount = 0;

io.on(‘connection’, socket => {
// Increment count of connected users
connectedUsersCount++;

// Emit the updated count to all connected sockets
io.emit('userCountUpdate', connectedUsersCount);

// Log a message indicating a new user connection
console.log('A user has connected');

// Handle disconnection
socket.on('disconnect', () => {
    // Decrement count of connected users
    connectedUsersCount--;

    // Emit the updated count to all connected sockets
    io.emit('userCountUpdate', connectedUsersCount);

    // Log a message indicating a user disconnection
    console.log('A user has disconnected');
}); });
70
Q

When it comes to managing WebSocket connections, particularly with Socket.IO, identifying the connected user can be challenging due to the lack of a traditional request-response cycle that you’d have with HTTP requests, What method can help bridge this gap?

A

parsing and decoding the cookie that contains the Passport session

71
Q

What does the method parsing and decoding the cookie that contains the Passport session technique do?

A

essentially replicates part of the authentication process that occurs in a typical HTTP request, but within the context of a WebSocket connection.

72
Q

What packages is a common setup for intregating Passport authentication with Socket.IO?

A

passport.socket.io
cookie-parser
session store like MongoStore

73
Q

What would the first step look like in the approach that enables you to authenticate WebSocket connections by accessing session information stored in MongoDB, thus identifying users connected through Socket.IO:
Hint:
Step 1: Setup Express, Passport, and Session Store

A

const express = require(‘express’);
const session = require(‘express-session’);
const MongoStore = require(‘connect-mongo’);
const passport = require(‘passport’);
const cookieParser = require(‘cookie-parser’);

const app = express();
const URI = “your_mongodb_connection_string”;

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

const sessionMiddleware = session({
secret: ‘yourSecret’,
resave: false,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: URI }),
cookie: {
// other cookie settings
},
key: ‘express.sid’ // This line explicitly sets the cookie name to ‘express.sid’
});

app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());

74
Q

In authenicating with Socket.IO, what would step 2 look like in code for Intregating Socket.IO with Passport and Session to configure Socket.IO to use the same session middleware, allowing it to access session data?

A

const server = require(‘http’).Server(app);
const io = require(‘socket.io’)(server);
const passportSocketIo = require(‘passport.socketio’);

// Then, when setting up passport.socketio, you make sure to use the same key:
io.use(passportSocketIo.authorize({
cookieParser: cookieParser, // the same middleware you register in express
key: ‘express.sid’, // the name of the cookie where express/connect stores its session_id, matching the session setup
secret: ‘yourSecret’, // the session_secret to parse the cookie
store: MongoStore.create({ mongoUrl: URI }), // using MongoStore as session store
success: onAuthorizeSuccess, // optional callback on success
fail: onAuthorizeFail, // optional callback on fail/error
}));

function onAuthorizeSuccess(data, accept) {
console.log(‘successful connection to socket.io’);
accept(null, true);
}

function onAuthorizeFail(data, message, error, accept) {
if (error)
throw new Error(message);
console.log(‘failed connection to socket.io:’, message);
accept(null, false);
}

io.on(‘connection’, function (socket) {
console.log(‘A user connected with sessionID:’, socket.request.user.logged_in);
// You can now access user data through socket.request.user
});

75
Q

In authenticating with Socket.IO, what would step 3 look like in code for running the server?

A

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(Server running on port ${PORT});
});

76
Q

Many chat rooms are able to announce when a user connects or disconnects and then display that to all of the connected users in the chat, what would this look like in the Server.js code?
Hint:
//Variable to store the count of connected users
//Handle new connection
Assuming you have access to the username authentication
//Increment the count of connected users
//Emit information about the new user
//Decrement the count of connected users when user disconnects
(//Emit information about the disconnected user)

A

let connectedUsersCount = 0; // Variable to store the count of connected users

io.on(‘connection’, function (socket) {
// Handle new connection
const username = socket.request.user.username; // Assuming you have access to the username after authentication

// Increment the count of connected users
connectedUsersCount++;

// Emit information about the new user
io.emit('userUpdate', {
    username: username,
    connectedUsers: connectedUsersCount,
    isConnected: true
});

// Decrement the count of connected users when user disconnects
socket.on('disconnect', function () {
    connectedUsersCount--;

    // Emit information about the disconnected user
    io.emit('userUpdate', {
        username: username,
        connectedUsers: connectedUsersCount,
        isConnected: false
    });
}); });
77
Q

In annoucing new users on the Client-side, how might you handle the ‘userUpdate’ event on the client-side in a chat room scenario?
Hint:
//Listen for ‘userUpdate’ event from the server
(//New user connected
//User disconnected)
//Update the count of connected users

A

// Listen for ‘userUpdate’ event from the server
socket.on(‘userUpdate’, function (data) {
if (data.isConnected) {
// New user connected
console.log(${data.username} has joined the chat.);
} else {
// User disconnected
console.log(${data.username} has left the chat.);
}

// Update the count of connected users
document.getElementById('connectedUsersCount').innerText = data.connectedUsers; });
78
Q

In chat intregation, to send and display chat messages both server-side and client-side, you’ll need to establish a communication flow between the server and clients using Socket.IO, Show how you can achieve this on the server-side(Node.js):

A

io.on(‘connection’, function (socket) {
// Handle new connection

// Listen for incoming messages from clients
socket.on('chatMessage', function (message) {
    // Broadcast the message to all connected clients, including the sender
    io.emit('chatMessage', { username: socket.request.user.username, message: message });
}); });
79
Q

In chat intregation, to send and display chat messages both server-side and client-side, you’ll need to establish a communication flow between the server and clients using Socket.IO, Show how you can achieve this on the Client-side(Browser):

A

<!DOCTYPE html>

<html>

<head>
<meta></meta>
<meta></meta>
<title>Chat Room</title>
</head>

<body>
<div></div>
<input></input>
<button>Send</button>



<script>
const socket = io();

        // Listen for incoming messages from the server
        socket.on('chatMessage', function (data) {
            // Display the message
            displayMessage(data.username, data.message);
        });

        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();

            if (message !== '') {
                // Send the message to the server
                socket.emit('chatMessage', message);

                // Clear the input field
                messageInput.value = '';
            }
        }

        function displayMessage(username, message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            messageElement.textContent = `${username}: ${message}`;
            messagesDiv.appendChild(messageElement);
        }
</script>

</body>

</html>