Use socket.io in expressjs routes instead of in main server.js file

后端 未结 2 1417
孤独总比滥情好
孤独总比滥情好 2020-12-08 04:58

I have express/nodejs api. I am adding socket.io feature to it. Currently all of my routes are in separate folders and I include them in server.js file and use them as app.u

相关标签:
2条回答
  • 2020-12-08 05:16

    There are multiple ways to share the io variable with route files.

    1. When you require() in your route file, pass it the io variable as a constructor argument.

    2. Use app.set("io", io) so you can then use let io = app.get("io") in any file that has access to the app object.

    3. Create a middleware that puts the io object on every req object 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);
    
    0 讨论(0)
  • 2020-12-08 05:42

    In server.js:

    module.exports.getIO = function(){
         return io;
    }
    

    In your route file:

    var theServer = require('<path to server.js>');
    var iovar = theServer.getIO(); //your io var
    
    0 讨论(0)
提交回复
热议问题