ExpressJS如何传递带有状态的对象(例如,连接)? [英] ExpressJS how do I pass objects with state (eg. connections)?

查看:25
本文介绍了ExpressJS如何传递带有状态的对象(例如,连接)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更是一个架构问题,而不是其他任何问题.我正在开发一个使用ExpressJS,Angular和Socket.io的项目,并且遇到了尝试保持socket.io实例化以便其他区域可以使用它的挑战.

This is more of an architectural question than anything. I am working on a project that uses ExpressJS, Angular, and Socket.io and have run into a challenge of trying to persist the socket.io instantiation so other areas can use it.

让我们跳到我拥有的东西上吧

Let's jump into what I have:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

在上面的代码中,io变量可用于创建侦听器,发送消息等.在另一个文件中,我有通过应用程序var传递的路由:

In the code above, the io variable can be used to create listeners, send messages, etc. In another file I have my routes that are passed the app var:

require('./app/routes')(app);

在我的路由中,我处理请求,并且在一种情况下,当POST进入时,我想在socket.io中向连接的客户端发送一条消息.如何使io变量可被其他区域访问?

In my routes I handle requests, and in one case when a POST comes in I want to fire off a message in socket.io to the connected clients. How do I make the io variable accessible to other areas?

注意:我将mongoose与mongodb一起使用,并注意到"mongoose.connect(db.url);"在服务器文件中被调用,然后在其他模块中,我可能需要mongoose.js和调用模型.他们如何在多个实例之间保持连接?

Note: I'm using mongoose with mongodb and noticed that "mongoose.connect(db.url);" is called in the server file, and then in other modules I can require the mongoose.js and call models. How do they maintain the connection across the multiple instantiations?

推荐答案

就像使用 app 变量一样,您只需传递它

Just like you do with app variable, you just pass it

require('./app/routes')(app, io);

然后在路线中,您将其捕获

and then in the routes, you catch it

module.exports = function(app, io) {

    app.get('something', function(req, res, next) {

        io.emit('something else');

    });

}

这篇关于ExpressJS如何传递带有状态的对象(例如,连接)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆