1

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);
            });
        });
    });
}
NoobSailboat
  • 109
  • 9
  • 1
    There is no "standard" way. It depends upon how you want to organize your modules. Here's [one method](https://stackoverflow.com/questions/38511976/how-can-i-export-socket-io-into-other-modules-in-nodejs/38514118#38514118) that is similar to yours. When more than one module wants to use socket.io [here](https://stackoverflow.com/questions/48063925/node-socket-io-socket-on-across-multiple-files/48071510#48071510) and [here](https://stackoverflow.com/questions/48633806/access-socket-emitter-with-socket-io-in-other-modules-nodejs-express/48636143#48636143) are some ideas. – jfriend00 Jun 22 '22 at 23:26

0 Answers0