Using socket.io modules in other JS files

505 Views Asked by At

The following is my app.js that I configured for socket.io functionality, The things are working as expected ,but now i want to use this socket functionality another js file from the same project, How to achieve this?

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(8080);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
1

There are 1 best solutions below

2
On

Just write var io = require('socket.io')(server); in each file where you want to use socket.io module. If you want to create shared functionality, create another module in your app with socket.io, ie.:

var io = require('socket.io')(server);

module.exports = function(options) {
  // your code here
}

If its not the answer for your question, please be more specific.