我希望我的应用程序有一个结构,但不知道如何从子路由器调用socket.io并将其附加到服务器快递
// app.js
var express = require('express')
, http = require('http')
, path = require('path'):
, i18n = require("i18n");
var app = express();
.
.
app.use(app.router);
require('./routes')(app);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express port " + app.get('port'));
});
// routes.js
module.exports = function (app) {
var rou_admin = require('./routers/admin')
, rou_login = require('./routers/login')
, rou_page = require('./routers/page')
, rou_logou = require('./routers/logout');
function restrict(req, res, next) {
if (req.session.user){
next();
} else {
res.redirect('/login');
}
}
//General
app.get('/', rou_page.page);
//Admin
app.get('/admin', rou_admin.admin);
//xxxx
app.get('/xxxx', rou_admin.xxxx);
//ssss
app.get('/ssss', rou_admin.ssss);
.
.
};
//路由/ admin.js
exports.admin = function(req, res){
res.render('index',{title: 'Chat Room'})
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
...code...
}
};
我怎么能这样做,如果你有更好的主意。 var io = require('socket.io')。listen(app);
答案 0 :(得分:1)
您已经获得了大部分解决方案。只需做一些改动:
routes.js
module.exports = function (app) {
var rou_admin = require('./routers/admin')(app), //pass app to routes/admin.js itself
路由/ admin.js
function admin(app)
{
admin.start= function(req, res){
res.render('index',{title: 'Chat Room'})
var io = require('socket.io').listen(app);
...code...
};
}
module.exports = admin;
这里只是定义了函数,你可以使用admin.start()来执行你的代码。