How to access io.emit() from routes/index? on express 4.15

This question already has an answer here:

  • express.js 4 and sockets with express router 2 answers

  • 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

    上一篇: Firebase FCM参考错误的云端函数

    下一篇: 如何从routes / index访问io.emit()? 在快递4.15上