Nodejs: access socket.io instance in express route files

I would like to be able to serve data to clients connected to socket.io server from express route files.

My app.js looks like this:

var express = require('express');
var app = express();

//routes
require('./routes/test')(app);

// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
  console.log('HTTP server listening on port 8000');
});

var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
    socket.join("test");
    socket.on('message', function(data){
       .....
    });
});
module.exports = app;

      

My test.js file :

module.exports = function(app){
    app.post('/test', function(req, res){
       .....
       //I would like here be able to send to all clients in room "test"
    });
};

      

+3


source to share


1 answer


Just add your io object as an argument to the routes module:

app.js :

var express = require('express');
var app = express();


// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
  console.log('HTTP server listening on port 8000');
});

var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
    socket.join("test");
    socket.on('message', function(data){
       .....
    });
});

//routes
require('./routes/test')(app,io);

module.exports = app;

      



test.js :

module.exports = function(app, io){
  app.post('/test', function(req, res){
    .....
    //I would like here be able to send to all clients in room "test"
    io.to('test').emit('some event');
  });
};

      

+15


source







All Articles