[英]Express 4 ans Socket.io - Access app.io in modules
Im a using socket.io and Express 4 and I have problems passing the io
to other modules. 我正在使用socket.io和Express 4,但在将
io
传递到其他模块时遇到问题。
In my app.js , I attach io to app like this: 在我的app.js中 ,我将io附加到应用程序,如下所示:
var express = require('express');
var socket_io = require('socket.io');
var app = express();
app.io = socket_io();
module.exports = app;
My server is defined in./bin/www not in app.js and io
is attached to the server like this: 我的服务器是在./bin/www中定义的,而不是在app.js中定义的,并且
io
像这样连接到服务器:
./bin/www: ./bin/www:
var app = require('../app');
var http = require('http');
server.listen(3000);
app.io.attach(server);
In my module I am trying to import app
to access app.io
but I probably have a circular dependancy problem because app
is an empty object. 在我的模块中,我尝试导入
app
以访问app.io
但由于app
为空对象,我可能遇到循环依赖问题。
module.js module.js
var app = require('../app');
console.log(app)
--> {}
I have tryed solutions suggested in this and this questions, but they are not working. 我已经tryed在建议的解决方案这个和这个问题,但他们没有工作。 I suspect the fact I am creating the server in ./bin/www might be the cause.
我怀疑我可能是在./bin/www中创建服务器的事实。
What can I do to access app
in other modules? 如何访问其他模块中的
app
?
You can try with this answer: Using socket.io in Express 4 and express-generator's /bin/www 您可以尝试以下答案: 在Express 4和express-generator的/ bin / www中使用socket.io
app.js app.js
// Socket.io
var io = socket_io();
app.io = io;
var routes = require('./routes/index')(io);
index.js index.js
module.exports = function(io) {
var app = require('express');
var router = app.Router();
io.on('connection', function(socket) {
(...)
});
return router;
}
Also try not to require app.js
from the modules 还要尽量不要从模块中获取
app.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.