简体   繁体   English

无法使用一个套接字模块将变量名从一个节点模块发送到另一个节点模块,以将其用作聊天应用程序的房间名称

[英]Cannot send variable name from one node module to another to use it as a room-name for chat application using socket.io

I am able to get the room name from user but as I use module.exports in another file to retrieve it shows undefined . 我可以从用户那里获得房间名称,但是当我在另一个文件中使用module.exports检索它时,它显示为undefined。 This might be because it is asynchronous. 这可能是因为它是异步的。

//roomcheck.js //roomcheck.js

var nsp = io.of("/gameroom");
nsp.on('connection', (socket) => {
socket.on('check', (data) => {
    if (rm.includes(data)) {
        roomname = data;
        console.log(roomname);
        console.log("Room exist!!!");
        socket.emit('success', 'room already made');
});

module.exports=roomname;

//userpage.js //userpage.js

var r=require('roomcheck.js');
console.log(r.roomname);

Expected - roomname entered by user. 预期 -用户输入的房间名称。

My output - undefined 我的输出 -未定义

  • Firstly, you are right, it is becouse it is asynchronous 首先,你是对的,因为它是异步的
  • Secondly you have set the module.exports itself to be the roomname, which means that module.exports is not an object it is the string itself 其次,您已将module.exports自身设置为房间名称,这意味着module.exports不是对象,而是字符串本身

So basically r is module.exports 所以基本上r是module.exports

If I were you I would make module.exports and object that has an onRoomCheck function to which I could pass a callback to 如果您是我,我将使module.exports和具有onRoomCheck函数的对象可以将回调传递给该对象。

Example code: 示例代码:

//roomcheck.js //roomcheck.js

var roomCheckCallback = ()=>{};
var nsp = io.of("/gameroom");
nsp.on('connection', (socket) => {
socket.on('check', (data) => {
    if (rm.includes(data)) {
        roomname = data;
        console.log(roomname);
        roomCheckCallback({roomname:roomname,exists:true});
        console.log("Room exist!!!");
        socket.emit('success', 'room already made');
    } else { roomCheckCallback({roomname:null,exists:false}); }
});
module.exports = {}
module.exports.onRoomCheck = function(callback){
    roomCheckCallBack = callback;
}

//userpage.js //userpage.js

var r=require('roomcheck.js');
r.onRoomCheck( (room)=> { console.log(room.roomname) } );

The solution to this is to make a delay by setTimeout function In roomcheck.js 解决方案是通过在roomcheck.js中使用setTimeout函数进行延迟

setTimeout(()=>{
module.exports=roomname;
},1000);

This provides a delay of 1 second and gives roomcheck.js to get the roomname and then export it 这提供了1秒的延迟,并提供了roomcheck.js来获取房间名称,然后将其导出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM