Using socket.io with express 4 generator

5.9k views Asked by At

New to node, so my apologies. I'm working on my app and I want to send the location using socket.io. I've found 1000 examples, but all refer to when express had no routes, and it all was at the app.js. All examples refer to chat applications. I was able to run an example piecing together several questions I searched but, I don't understand how to get the io that I finally got working on my app.js to interact with my index.js so I can use it with multiple emit parameters. express.io is outdated and I can't find anything current. On bin/www

/**
 * Socket.io
 */
var io = app.io
io.attach( server );

My app.js

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

var app = express();

var io = socket_io();
app.io = io;

So I can use:

io.on('connection', function (socket) {
    console.log('IO Ready');
});

I don't know how to use the sockets on my index.js (routes), I can't modularize it.

Thanks in advance.

1

There are 1 answers

0
Patosai On BEST ANSWER

I have to say, I think the default generated project is bad for a socket.io setup. The node http.Server var is all the way in bin/www and not in app.js.

So the first thing is to move all the relevant stuff from bin/www to app.js. Mainly you just need

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

just like in the socket.io docs.

Now with io in app.js, we can use that when the routes are required. I forgot how exactly the default routes are set up, but I think they set up an app and just export it. Instead, you can set up something like

module.exports = function(app, io) {
    io.on('connection', function(socket) {
        console.log('connected!');
    }

    app.get('/foo', function() {
        ...
    }
}

And now when you require the routes, instead of having the default

var index = require('./routes/index');
app.use(index);

or something of that accord, you can just do

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

And that's how you get io into your routes. Or at least how I do it anyway.