I am setting up foundations for a websocket app using node.js
, express
and socket.io
. I decided it would be elegant to place the code that sets up socket.io
in a separate module, so my server.js
file could be smaller, calling require
for socket.io
setup duties.
// server.js
// set up ======================================================================
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 80;
// routes ======================================================================
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// socket.io controller ========================================================
require('./app/ws-controller.js')(io);
// launch ======================================================================
server.listen(port, function () {
console.log('Server listening on port ' + port + '!');
});
In my ws-controller.js
file I placed some code to begin experimenting with socket.io
.
// app/ws-controller.js
module.exports = function(io) {
var numClients = 0;
io.on('connection', function (socket) {
numClients++;
console.log(numClients);
});
}
The client script embedded in index.html
is minimal.
// client side script
var port = 80;
var socket = io.connect('http://127.0.0.1:' + port);
Now to the point. Upon opening new browser tabs pointing to localhost
, the server logs to the console increasing number numClients
. How is that actually working? I was sure that numClients
would be out of scope and expected to see an exception on the console. When the callback function bound to on connection
events fires it shouldn't see the numClients
variable since it is not global nor private to io
object, right? What is actualy happening here?