如何在nodejs中创建全局HashMap

How to create a global HashMap in nodejs?

本文关键字:创建 全局 HashMap nodejs      更新时间:2023-09-26

以下是我的初始定义,所有函数都在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')

但我刚刚将密钥username的值设置为socket中的值。但它后面的一行返回一个未定义的。我使用了全局关键字。但仍然会出错。

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

您要做的是在getSocket(username)函数中将检查if(global.user_to_Socket_Map.has(username) == "true")更改为if(global.user_to_Socket_Map.has(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);
    }
}