accessing required modules from other modules

I have a bare-bone express application, exactly the one that is created with the express command.

I have installed socket.io and attached it to my server, like this:

var app = express(),
    server = http.createServer(app),
    io = io.listen(server);

server.listen(8000);

Now, I also have the routes files, which is called like this:

app.get('/', routes.index);

Inside this module I have the following function:

exports.index = function(req, res){
  socket.emit('news', { message: "foo" });
};

This obviously leads to a 500 reference error, because the routes file is an exportable module, and obviously has no idea what the socket is, as it is located in the app.js file.

Is there a way I can access this socket object from this, or any other file? Please note that it is attached to the express generated app. Here is a link to said project: http://jsfiddle.net/E27yN


extra: what about getting/setting session data?

Thanks in advance.

If I'm reading this correctly, I had a very similar problem: Handling Node.js Async Returns with "require" (Node ORM)

The way I resolved it was by putting a function call to the require, and returning that function in my exports, then that was accessible via that local variable. In your case, I think it'd be something like this:

var routes = require("routes.js")(io);
console.log(routes.index()); // will log return of the function "index" in routes.js.

// in routes.js
module.exports = function(io) {
  var exports = this;
  exports.index = function(req,res,io) {
    // now io.socket is available to routes
    console.log(io); 
  }
  return exports;
}

Now you can access whatever you've exported by using that variable. So getting and setting session data would be a matter of getting that info to/from the proper place and modifying it in your parent file (usually whatever you're launching with node, like app.js or what have you).

Hope this helps!

EDIT: After discussing this in the comments, I think the problem is you're trying to use express and socket.io on the same port.

The example they give in your link (http://socket.io/#how-to-use) actually shows that they are serving up index.html from app.get("/"). Index.html includes the socket.io script file () which is by default served up when you start your socket server.

That would look like this jsfiddle: http://jsfiddle.net/Lytpx/

Note that you serve up the index.html page through express, but your socket service actually serves up /socket.io.js which then makes connection calls to the listening socket service (note, you may want to change localhost in your io.connect call in index.html to whatever your server is).