NodeJS模块之间的“共享”对象

时间:2018-06-26 15:15:58

标签: node.js socket.io

我是NodeJS开发的新手,并且正在使用socket.io库进行一些测试。基本上,我想做的是在客户端(Angular 6 Web应用程序)和服务器之间建立一个socket.io连接,并在新用户连接时广播一条消息。

现在,代码非常简单,这就是我所拥有的:

app.js

var express = require('express');
var http = require('http');
var socketIO = require('socket.io');

// Routes
var twitterRoutes = require('./routes/user');

var app = express();

var server = http.Server(app);

var io = socketIO(server);  // <== THIS OBJECT IS WHAT I WANT TO USE FROM THE ROUTES

[ ... ]

io.on('connect', (socket) => {
    console.log('New user connected');

    socket.on('disconnect', (reason) => {
        console.log('User disconnected:', reason);
    });

    socket.on('error', (err) => {
        console.log('Error in connection: ', err);
    });
});

我想在io路由内使用user对象,但是我不知道该怎么做:

routes / user.js

var express = require('express');

var config = require('../config/config');

var router = express.Router();

router.post('/login', (req, res, next) => {

    // DO ROUTE LOGIC

    // I WANT TO BROADCAST THE NEW LOGGED USER USING io.broadcast.emit, BUT DON'T KNOW HOW
    // <=====
});

我该怎么办?预先感谢,

3 个答案:

答案 0 :(得分:0)

不确定这是否是最好的方法,但是您可以使用中间件在请求处理程序之间共享内容

// define and use a middleware
app.use(function shareIO(req, res, next) {
  req.io = io;
  next();
})

然后,您可以在请求处理程序中使用req.io

router.post('/login', (req, res, next) => {

    // DO ROUTE LOGIC

    req.io.emit('event')
});

答案 1 :(得分:0)

您可以通过将IO变量注入函数中来完成所需的操作

    // app.js
    var app = express();
    var server = http.Server(app);
    var io = socketIO(server);
    server.use(require('./router')(io))
    ...

    // router.js
    module.exports = function makeRouter(io) {
      var router = express.Router();
      router.post('/login', (req, res, next) => {
        // do something with io

      }
      return router
    }

答案 2 :(得分:0)

我不知道这是否是最佳实践,但是我已经将io对象分配给global对象的属性,并且可以在应用程序的任何位置访问它。这就是我所做的:

app.js

var io = socketIO(server);

global.ioObj = io;

routes / user.js

router.post('/login', (req, res, next) => {

  // DO ROUTE LOGIC

  if (global.ioObj) {
    global.ioObj.sockets.clients().emit('new-message', { type: 'message', text: 'New user has logged in' });
  }

});