6

I have the app.js code:

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

io.on('connection', function(socket){

  socket.on('newRideAdded', function(exclude){
    io.emit('newRideAdded', exclude);
  });

  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

});

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.use(express.static(__dirname + '/public/'));

app.use('/rides', require('./routes/rides'));
app.use('/user', require('./routes/user'));

server.listen("8080", function() {
  console.log("Connected to db and listening on port 8080");
});

And I want to move the socket io code to its router's page.

That is the router page:

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs("ride4you", []);

router.post('/getRides', function(req, res, next) {
  db.rides.find(function(err, docs) {
    res.json(docs);
  });
});

// rest of the restapi in this page.

// I want socket code to be here

module.exports = router;

As you can see i have each socket emits in each router's page and I already have module.exports in routers page.

How can it be done?

Thanks.

1 Answers1

22

Using Express 4, in your app.js file you can use

app.set('socketio', io);

Then in your router or controller, you can use

router.post('/getRides', function(req, res, next) {
    var io = req.app.get('socketio');

    io.to(//socket.id//).emit("message", data);

    db.rides.find(function(err, docs) {
        res.json(docs);
    });
};

This is a clean way of passing the reference along.

John Spiteri
  • 564
  • 6
  • 18
  • 1
    This is a little unrelated but that looks like the easiest way ive ever seen to pass a socket.io connection object around the express application that avoids continuously passing it down to routes etc. – Freddie Nov 12 '17 at 20:48
  • Let me know, instead of emit from client side, then receive in node server and re emit and then receive in client side, you simplified this, and now instead of two ways it is just one way: emit from nodejs server, then receive in client side. Right? Well, I have tested this and works awesome. But just one thing, the on connection function does not work: io.on('connection', function(socket){ socket.on('newRideAdded', function(exclude){ maybe you know why? –  Nov 12 '17 at 21:49