user1576978 user1576978 - 4 months ago 174
Node.js Question

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

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-genrator 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 sintax, 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 havin this /bin/www file as starting point of my app?

Answer

It turns out it really was some basic sintax problem.... I got these lines from this socket.io chat tutorial...

on ./bin/www, just after var server = app.listen(.....)

var io = require('socket.io').listen(server);
require('../sockets/base')(io);

so now I create the ../sockets/base.js file and put this little fellow inside it:

module.exports = function (io) { // io stuff here... io.on('conection..... }

Yeah! Now it works... So i guess i really had no option other than starting socket.io inside /bin/www , because that is where my http server was started. The goal is that now i can build socket functionality in other file(s), keeping the thing modular, by require('fileHere')(io);

<3