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.
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 inapp.js
.So the first thing is to move all the relevant stuff from
bin/www
toapp.js
. Mainly you just needjust like in the socket.io docs.
Now with
io
inapp.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 anapp
and just export it. Instead, you can set up something likeAnd now when you require the routes, instead of having the default
or something of that accord, you can just do
And that's how you get
io
into your routes. Or at least how I do it anyway.