NodeJS Express - 如何从控制器

时间:2017-01-26 13:15:55

标签: node.js express socket.io

我的app.js文件中有一个socket.io服务器

const port = process.env.PORT || 3000;
const server = https.createServer(options, app);
const io = require('socket.io');
const ios = io(server);

const routes = require('./routes/index');
app.use('/', routes);

从该文件中,我知道如何获取房间列表

ios.sockets.adapter.rooms

现在我需要从我的一个路径文件中访问ios(其中我也实现"控制器"逻辑,我稍后会重构)

# routes/index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    //
    // I'd like to check ios.sockets.adapter.rooms HERE
    // HOW DO I DO THAT?
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

这是一种方式,也许没有最好的方法 您需要将 io 实例传递给路由器。我使用包装器功能。

//router.js
const router = express.Router();

const wrapper = function(io){
   //work with your router
   router.get('/endpoint',(req,res) => {

   });
});

export default wrapper;
------------------------------------

//server.js
import yourRouter from "./yourRouter";
//socket
const server = http.createServer(app);  
const io = socket(server);

//express
app.use(logger('dev'));
app.use(bodyParser.json());

//here you can pass the instance
app.use(yourRouter(io)); 

使用中间件

的另一种方法
//server.js
// middleware
app.use((req, res, next) => {
    req.io = io;
    next();
});

app.use(yourRouter);

//router.js
import express from 'express';
const router = express.Router();

router.get('/payments/cancel', (req, res) => {    
     //get the instance
     const io = req.io;     
     res.send('Ok');    
});
export default router;

第二个更干净,不需要包装功能。