I'm trying to use Socket.io with Node.js and emit to a socket within the logic of a route.
I have a fairly standard Express 3 setup with a server.js file that sits in the route, and then I have an index.js which sits in a routes folders that exports all the pages/publically accessible functions of the site. So they look like:
exports.index = function (req, res) {
res.render('index', {
title: "Awesome page"
});
};
with the routing defined in server.js like:
app.get('/',routes.index);
I'm assuming I have to create the socket.io object in the server.js, since it needs the server object, but how can I access that object and emit to it from the index.js export functions?
aarosil's answer was great, but I ran into the same problem as Victor with managing client connections using this approach. For every reload on the client, you'd get as many duplicate messages on the server (2nd reload = 2 duplicates, 3rd = 3 duplicates, etc).
Expanding on aarosil's answer, I used this approach to use the socket object in my routes file, and manage the connections/control duplicate messages:
Inside Server File
Inside routes file
There is a better way to do this now with Express 4.0.
You can use app.set() to store a reference to the
io
object.Base configuration:
Inside route or middleware:
Information about
app.set()
andapp.get()
is below:Source: https://expressjs.com/en/api.html#app.set
You can set up your routes file as a function, and pass the Socket.IO object when requiring the file.
Then require routes like this:
Whats wrong with just using
module.parent.exports.server
would also work if you exported server in the parent module.