将app和io传递给模块

时间:2015-04-14 08:17:16

标签: javascript node.js express module socket.io

来自我的server.js

var app  = require('express')();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);

server.listen(port,function (){
       console.log('Listening is at ' + port);  
});

现在我正尝试将appio传递给模块:

require('./routes/moduleX.js')(app,io);

./routes/moduleX.js

module.exports = function(app,io){

      app.get('/moduleXX',function(req,res){ /
           res.render('moduleXX.ejs');

           var dataToBeSent = {
                  YYYY: 10,
                  NNNNN: 5,
                  TTTTT: [2,4,5,6,7],
           };

           io.sockets.on('connection', function (socket) {
                  console.log('Client Connected');
            socket.emit('subReady', { prep: dataToBeSent });
           });      

      });
     }

我收到TypeError: Cannot read property 'sockets' of undefined

我的问题是为什么io在这里未定义?以及如何正确地做到这一点。

1 个答案:

答案 0 :(得分:-1)

更改以下代码

io.sockets.on('connection', function (socket) {
    console.log('Client Connected');
    socket.emit('subReady', { prep: dataToBeSent });
});      

io.on('connection', function (socket) {
    console.log('Client Connected');
    socket.emit('subReady', { prep: dataToBeSent });
});