NodeJS ReferenceError:未定义io

时间:2014-02-18 13:43:28

标签: javascript node.js express

我开始使用节点JS并面临io lib的问题,这里的错误是:

ReferenceError: io is not defined
     at exports.index (D:\dev\lib\index.js:9:5)
     at callbacks (D:\dev\node_modules\express\lib\router\index.js:164:37)
     at param (D:\dev\node_modules\express\lib\router\index.js:138:11)
     at pass (D:\dev\node_modules\express\lib\router\index.js:145:5)
     at Router._dispatch (D:\dev\node_modules\express\lib\router\index.js:1 73:5)
     at Object.router (D:\dev\node_modules\express\lib\router\index.js:33:1 0)
     at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
     at Object.methodOverride [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:49:5)
     at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
     at Object.urlencoded [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:51:37)

以下是我的app.js文件的内容:

var express = require('express'); 
var path = require('path');

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

app.set('port', process.env.PORT || 8080); app.set('views',
path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon()); app.use(express.logger('dev'));
app.use(express.json()); app.use(express.urlencoded());
app.use(express.methodOverride()); app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', require('./lib').index);

server.listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port')); 
});

我的文件lib / index.js:

exports.index = function(req, res){
    res.render('index');
    io.sockets.on('connection', function (socket) {
        socket.emit('message', 'welcome');
    });
};

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

您需要将io传递到您的路线:

exports.index = function(io) {
    return function(req,res) {
        res.render('index');
        io.sockets.on('connection', function (socket) {
            socket.emit('message', 'welcome');
        }
    }
}

然后将其称为app.get中的函数:

app.get('/', require('./lib').index(io));

我建议使用其他变量声明require('./lib')部分。这将允许代码重用和更好的可读性(相对于每个人)。

var /*other variables*/,
    lib = require('./lib');

然后你可以做app.get('/', lib.index(io));

只是一个想法。