JohnSnow
JohnSnow

Reputation: 7121

Using socket.io in routes other than server/app.js

Hi I am trying to use socket.io in a file other than my main server.js file where I first set it up like so:

const app = require('express')();
const http = require('http').createServer(app);
const mongoose = require('mongoose');
const io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});

Since I am setting it up in my server.js file I have to listen for events in this file and therefore the callback function will only have access to the scope of this file. However I need to use this in another file in my routes that I have set up like so for example:

app.use('/', home);

I have read both this and this and neither one has helped me.

Thanks.

Upvotes: 1

Views: 402

Answers (1)

Vaibhav Patil
Vaibhav Patil

Reputation: 2983

Write your socket logic in another file inside a function and call it from server.js.

socket.js

const io = require('socket.io');

module.exports = function(server) {
io(server).on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});
}

and in server.js

const app = require('express')();
const http = require('http').createServer(app);
const mongoose = require('mongoose');

require("./socket")(http)

Upvotes: 1

Related Questions