I'm using socket.io in my express application. I have one route and view that uses socket.io on the client-side browser.
Sooner or later the socket.io code will get larger and I would like to modularize it.
This is what I have so far and it works just fine but I am wondering what is the conventional way to modularize socket.io in an express.js app?
server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, (req, res) => {
console.log(`Listening on port: ${PORT}`);
});
app.js (took out unnecessary things)
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const { socketIo } = require('./utilities/socket.io');
const roomRoutes = require('./routes/rooms');
/* Middleware */
app.get('/', (req, res) => {
res.render('index');
});
// Routes
app.use('/users', userRoutes);
app.use('/rooms', roomRoutes);
socketIo(io);
module.exports = http;
./utilities/socket.io
module.exports.socketIo = async (io) => {
io.on('connection', (socket) => {
socket.on('join-room', (roomId) => {
socket.join(roomId);
socket.on('chat-message', msg => {
io.to(roomId).emit('chat-message', msg);
});
});
});
}