There are multiple ways to share the io variable with route files.
-
When you
require()in your route file, pass it theiovariable as a constructor argument. -
Use
app.set("io", io)so you can then uselet io = app.get("io")in any file that has access to theappobject. -
Create a middleware that puts the
ioobject on everyreqobject so you can access it from there any time.
Here’s an example of passing it as a constructor argument to the router file:
let server = app.listen(3000);
let io = require('socket.io')(server);
// load other routers
app.use(require("./someRouterFile.js")(io));
// in someRouterFile.js
const express = require('express');
module.exports = function(io) {
let router = express.Router()
// define routes
// io is available in this scope
router.get(...)
return router;
}
Here’s an example of the app.set() scheme:
let server = app.listen(3000);
let io = require('socket.io')(server);
app.set("io", io);
Then, anywhere in your routes that you have access to the app object, you can get it with:
let io = app.get("io");
Here’s an example of using a middleware to set the io object onto every req object so it’s available from all routes.
let server = app.listen(3000);
let io = require('socket.io')(server);
// place this middleware before any other route definitions
// makes io available as req.io in all request handlers
app.use(function(req, res, next) {
req.io = io;
next();
});
// then in any express route handler, you can use req.io.emit(...)
Here’s an example of using an argument to the module constructor without middleware:
// in mysocket.js
module.exports = (io) => {
console.log('IO: ', io);
io.on('connect', socket => {
// handle various socket connections here
});
// put any other code that wants to use the io variable
// in here
};
Then, in your main file:
let server = app.listen(3000);
let io = require('socket.io')(server);
// initialize my socketio module and pass it the io instance
require('./mysocket.js')(io);