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

前端之家收集整理的这篇文章主要介绍了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 
  });
}
原文链接:https://www.f2er.com/js/158721.html

猜你在找的JavaScript相关文章