I have an express node app, and I'm trying to keep my code neat by not having all the socket.io stuff in app.js
I don't know the best way to go about this. Here is my initial thought which doesn't feel like the cleanest one
// app.js
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, url = require('url')
, somePage = require('./routes/somePage.js')
, path = require('path');
app.configure(function(){...});
app.get('/', somePage.index);
and the route
// somePage.js
exports.index = function (req, res, server) {
io = require('socket.io').listern(server)
res.render('index',{title: 'Chat Room'})
io.sockets.on('connection', function(socket) {
...code...
}
}
I feel like I'm close but not quite there
I don't know if I'm reading that right but it looks like you are starting a socket server on every request for
/
, which I'm frankly a little surprised works at all.This is how I'm separating out the socket.io code from app.js (using express 3.x which is a bit different than 2.x):
Hope that helps!
a similar approach is to pass
app
into index.js file and initiate http and socketio server there.Since
app
is passed into index.js file, we can do theapp.get()
routing stuff inside index.js, as well as connecting socketio