Friday, 17 March 2017

Separating socket.io event logic into module

I have seen a couple of questions referencing this issue however was not able to get this working.

I have an app that is running express for both API routes as well as socket real time app.

I would like to keep my server.js file "clean" and have all the socket related events in a separate file. I also want to be able to fire an event from within my route files.

My server.js loks like this:

const dotenv = require('dotenv/config');
const express = require('express');
const bodyParser = require('body-parser');
const socketIO = require('socket.io');
var http = require('http');
const _ = require('lodash');
const path = require('path');
const publicPath = path.join(__dirname, '../public');


var {mongoose} = require('./db/mongoose');
var {ObjectID} = require('mongodb');
var {authenticate} = require('./middleware/authenticate');
var {socketEvents} = require('./middleware/socketEvents')(io);
var multiparty = require('connect-multiparty'),
  multipartyMiddleware = multiparty();

var app = express()
var serv = require('http').createServer(app)
var io = socketIO.listen(serv)


var PORT = process.env.PORT || '80';
app.use(bodyParser.json());
app.use(multipartyMiddleware);
app.use(express.static(publicPath));


serv.listen(PORT, () => {
  console.log('Started on port: ' + PORT);
});

module.exports = {
  app
};

I would like to have a socketEvents.js file that includes:

io.on('connection', (socket) => {
  console.log('New user connected');

//all socket events here

});

How can I accomplish this?



via dwax

No comments:

Post a Comment