javascript – 将socket.io共享给其他模块给出了空对象

我试图在不同的node.js模块中共享socket.io的套接字对象,虽然我失败并获得空对象
Cannot call method 'on' of undefined

我的代码

app.js

var express = require('express'),app = express();

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

var routes = require('./routes'),path = require('path'),RSS = require('./routes/RSS')

// ...

exports.io = io;

路线/ RSS.js

io = require(__dirname + '/../app');

console.log(io);
io.sockets.on('connection',function(
  console.log("Connection on socket.io on socket");
  // .. do stuff 
});

这是我得到的输出

$node app.js                                                                                                    
   info  - socket.io started
{}

/home/XXX/programming/nodejs/node-express-aws/routes/RSS.js:10
io.sockets.on('connection',function(socket){
           ^
TypeError: Cannot call method 'on' of undefined
    at Object.<anonymous> (/home/XXX/programming/nodejs/node-express-aws/routes/RSS.js:10:12)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/XXX/programming/nodejs/node-express-aws/app.js:9:10)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)

虽然我已经尝试过,但我只能在一个(app.js)文件中使用socket.io

var express = require('express'),RSS = require('./routes/RSS')

// ...

io.sockets.on('connection',function(socket){
  logger.debug("Connection on socket.io on socket");
  socket.emit('news',{will: 'be recived'});
});

解决方法

因为在app.js中你有:
exports.io = io;

然后你需要像这样使用它:

var app = require('../app');
var io = app.io;

也就是说,您将一个名为io的属性附加到模块,因此当您需要该模块时,您将获得一个具有io属性集的对象.

你也可以这样做

module.exports = io;

然后离开RSS.js就像现在一样.

总而言之,如果您使用Node运行app.js,您会更常见地将io对象注入到其他模块中(而不是相反);例如:

app.js

var express = require('express'),RSS = require('./routes/RSS')

// ...

RSS(io); // pass `io` into the `routes` module,// which we define later to be a function
         // that accepts a Socket.IO object

路线/ RSS.js

module.exports = function(io) {
  io.sockets.on('connection',function(
    console.log("Connection on socket.io on socket");
    // .. do stuff 
  });
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...