如何在nodejs中创建全局HashMap?

时间:2015-11-30 15:32:29

标签: javascript node.js socket.io global

这是我的初始定义,所有函数都在server.js中的一个文件

var HashMap = require('hashmap');
global.user_to_Socket_Map = new HashMap();
global.socket_to_user_Map = new HashMap();


function makeOnline(username,socket)
{
    socket.emit("test","hi");

    if(global.user_to_Socket_Map.has(username) != "true"){
        console.log("Setting callee socket of "+username
            + 'socket ' + socket);
        global.user_to_Socket_Map.set(username, socket);
        getSocket(username).emit('test','hi2')
        console.log("Setting callee socket of "+username);
        global.socket_to_user_Map.set(socket, username);
        global.userInCall_Map.set(username, "false");
    }
 }

这是我的getSocket函数

function getSocket(username)
{
    console.log("Getting callee socket of "+username);
    if(global.user_to_Socket_Map.has(username) == "true"){
        console.log("Actually Getting callee socket of "+username);
        return global.user_to_Socket_Map.get(username);
    }



}

所以,我得到的错误是TypeError: Cannot call method 'emit' of undefined at line 25,即此函数调用getSocket(username).emit('test','hi2')

但我刚刚将密钥用户名的值设置为socket中的值。但在它返回未定义之后的一行。我使用了global关键字。但仍然得到错误。

1 个答案:

答案 0 :(得分:0)

您正在将布尔值与字符串进行比较。函数global.user_to_Socket_Map.has(username)返回布尔值,而不是字符串。因此,检查if(global.user_to_Socket_Map.has(username) == "true")将始终为false,因此getSocket(username)将始终返回undefined

您要做的是将if(global.user_to_Socket_Map.has(username) == "true")内的支票if(global.user_to_Socket_Map.has(username))更改为getSocket(username),如下所示:

function getSocket(username)
{
    console.log("Getting callee socket of "+username);
    if(global.user_to_Socket_Map.has(username)){
        console.log("Actually Getting callee socket of "+username);
        return global.user_to_Socket_Map.get(username);
    }
}