1

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?

Community
  • 1
  • 1
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

1 Answers1

0

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

thomasxd24
  • 55
  • 7