How to access io.emit() from routes/index? on express 4.15
This question already has an answer here:
I guess you have generated the app using express generator which creates app.js and bin/www files, There is a circular dependency issue to use io object inside routes. Here's what you can do,
Inside app.js
app.io = require('socket.io')(); // initialize io, attach server in www
// use socket events here
app.io.on('connection', function(socket){
// do whatever you want
})
// you can pass app.io inside the router and emit messages inside route.
const userRoute = require('./routes/user')(app.io);
app.use('/users', userRoute);
Inside bin/www
var io = app.io;
var server = http.createServer(app);
io.attach(server);
Now here's how router looks like, user.js
module.exports = function(io){
router.get('/', function(req, res, next){
io.emit("message", "your message");
res.send();
})
// edited
return router;
}
Note: I havent practically tried it yet.
But Can u try this pattern instead?
In www.js
module.exports = function(io) {
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
}
In index.js
var server = http.createServer(app);
io = require('socket.io')(server);
require('./wwww.js)(io);
链接地址: http://www.djcxy.com/p/33038.html