Using socket.io in Express 4 and express-generator's /bin/www

user1576978 picture user1576978 · Jul 7, 2014 · Viewed 54.8k times · Source

So here is the deal: I'm trying to use socket.io in an express project. After Express Js 4 was lauched, i've updated my express-generator and now the app initial functions goes into ./bin/www file, including those vars (www file contents: http://jsfiddle.net/avMa5/ )

var server = app.listen(app.get('port'), function() {..}

(check it by npm install -g express-generator and then express myApp

that being said, let's remember how socket.io docs ask us to fire it:

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

Ok but i can't do it inside app.js, like recommended. This should be done in ./bin/www in order to work. in ./bin/www this is what i can do to get it working:

var io = require('socket.io')(server)

Ok this works, but i can't use the io var anywhere else, and i really don't want to put my socket.io functions on www file.

I guess this is just basic syntax, but I can't get this to work, not even using module.exports = server or server.exports = server nor module.exports.io = app(io) on www file

So the question is: how can i use socket.io having this /bin/www file as starting point of my app?

Answer

Gabriel Hautclocq picture Gabriel Hautclocq · Feb 4, 2015

I have a solution for making socket.io available in app.js.

app.js:

var express      = require( "express"   );
var socket_io    = require( "socket.io" );

// Express
var app          = express();

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

(...)

// socket.io events
io.on( "connection", function( socket )
{
    console.log( "A user connected" );
});

module.exports = app;

// Or a shorter version of previous lines:
//
//    var app = require( "express"   )();
//    var io  = app.io = require( "socket.io" )();
//    io.on( "connection", function( socket ) {
//        console.log( "A user connected" );
//    });
//    module.exports = app;

bin/www:

(...)

/**
 * Create HTTP server.
 */

var server = http.createServer( app );


/**
 * Socket.io
 */

var io     = app.io
io.attach( server );

(...)

This way, you can access the io variable in your app.js, and even make it available to your routes by defining module.exports as a function which accepts io as a parameter.

index.js

module.exports = function(io) {
    var app = require('express');
    var router = app.Router();

    io.on('connection', function(socket) { 
        (...) 
    });

    return router;
}

Then, pass io into the module after it is setup:

app.js

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

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