将变量调用到不在nodejs和express中工作的不同路由

时间:2015-05-20 07:40:08

标签: javascript node.js express socket.io socket.io-1.0

我的app.js设置如下:

app.js

 var express = require('express');
 var socket_io = require("socket.io");
 var app = express();
 
 //Our route variables.
 var routes = require('./routes/index');
 var users = require('./routes/users');
 var work = require('./routes/work');
 

 // Socket.io
 var io = socket_io();
 app.io = io;

 var playground = require('./routes/playground')(io);

 //CODE I WANT MOVED TO playground.js!
 //Socket IO playground
 io.on('connection', function(socket) {
   console.log('a user connected');
   socket.on('chat message', function(msg) {
     io.emit('chat message', {
       message: msg.message,
       nickname: msg.nickname
     });
   });

   socket.on('disconnect', function() {
     console.log('a user disconnected');
   });
 });

我被告知我可以将.io发送到我的路线 playground.js ,就像这样:

var playground = require('./routes/playground')(io);

但是我收到以下错误无法调用'IndexOf'未定义的方法

我不希望我的socket.io代码在app,js中,因为我不希望app.js变得混乱。 (代码会超时)我只想在playground.js中使用socket.io,因为我的所有测试应用都会在那里。如果我能说得更清楚,请告诉我

playground.js

var express = require('express');
var router = express.Router();


module.exports = function(io) {
  io.on('connection', function(socket) {
    console.log("connection made!");
  });
};

router.get('/', function(req, res, next) {
  res.render('playground');
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

playground.js最后一行module.exports = router;取代之前的module.exports声明。 尝试:

//routes/playground.js
var express = require('express');
var router = express.Router();


module.exports = function(app, io) {
  io.on('connection', function(socket) {
    console.log("connection made!");
  });
};

router.get('/', function(req, res, next) {
  res.render('playground');

app.use('/', router);
});

并在您的应用中尝试require('./routes/playground')(app, io);