Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs : access socket.io instance in express routes files

I would like to be able to emit datas to clients connected to socket.io server from my express routes 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"
    });
};
like image 498
Bobby Shark Avatar asked Sep 06 '14 13:09

Bobby Shark


1 Answers

Simply inject your io object as an argument into 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');
  });
};
like image 191
roterski Avatar answered Sep 27 '22 22:09

roterski