简体   繁体   中英

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.

In my app.js , I attach io to app like this:

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:

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.

module.js

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

console.log(app)
--> {}

I have tryed solutions suggested in this and this questions, but they are not working. I suspect the fact I am creating the server in ./bin/www might be the cause.

What can I do to access app in other modules?

You can try with this answer: Using socket.io in Express 4 and express-generator's /bin/www

app.js

// Socket.io
var io = socket_io();
app.io = io;

var routes = require('./routes/index')(io);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM