0

I have a project set up where in my bin/www file I have my node server set up with the following line which works:

const server = http.createServer(app);

I am working on setting up socket.io so I would like to make another file called socket.js and in there do all the socket.io set up but I need to be able to get access to my server variable. I tried to export my server variable like this:

module.exports = server;

and then use it in my new file like this:

const server = require("./bin/www");
const io = require('socket.io')(server); //server doesn't seem to be working here

io.on("connection", socket => {
    socket.on('sendMessage', data => {
        socket.join(socket.id, () => {
            console.log('Joined group');
            io.sockets.in(socket.id).emit('sendMessage', data)
        });
    });
});

But it doesn't look like this is setting up the socket on the server as I am getting the following error:

GET /socket.io/?EIO=3&transport=polling&t=N1HOkXK which happens when it isn't set up correctly.

Martheli
  • 931
  • 1
  • 16
  • 35

2 Answers2

1

Instead of exports your server you can send server reference from bin/www to start your socket server.

Your bin/www

const express = require('express');
const socket = require('./socket');
const app = express();

const server = https.createServer(app);

sockets.startSocketServer(server);

Your socket.js file

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

module.exports = {
    startSocketServer: function (server) {
        io = socketio.listen(server);
        io.sockets.on('connection', function (socket) {
            socket.on('sendMessage', data => {
                socket.join(socket.id, () => {
                    console.log('Joined group');
                    io.sockets.in(socket.id).emit('sendMessage', data)
                });
            });
        })
    }
}
0

Using a function with exports:

In your bin/www file:

module.exports = init;

function init(){
  // All other relevant code for your server declaration
  return http.createServer(app);
}

In your new file:

const server = require("./bin/www")();

Using a variable with exports:

In your bin/www file:

exports.server = server;

In your new file:

const server = require(".bin/www").server;
campbellg54
  • 66
  • 1
  • 6
  • is there a way to export only the variable without putting it into a function? – Martheli Feb 17 '20 at 04:47
  • You could and I have added the option for that, however, in this case it looks more suited to using a function as it would ensure the `http.createServer(app)` function call is executed as the variable is used. – campbellg54 Feb 17 '20 at 04:53