Search code examples
node.jswebsocketsocket.iochat

How to keep track of users by identifier using Node.JS


I am listening to a small socket.io chat application. Every time a user joins, the server emits a message with the user's name and an id generated on the spot. However, when the user sends a message, the server only broadcasts the message with the userid, and without the username. This snippet of code shows the events that are triggered when a user connects and sends a message.

    socket.on('chat_new_user', (data) => {
        var json = JSON.parse(data);
        console.log('new user!')
        console.log(json.userid)
        console.log(json.username)

    });
    socket.on('chat_new_message', (data) => {
        var json = JSON.parse(data);
        console.log(`${json.userid} - new message!`)
        console.log(json.msg)

My issue is, how can I log the user's name to my console when he sends a new message, even though I only have the userID in the message json?


Solution

  • You may need to store the users data in an array

        const users = []
        
        socket.on('chat_new_user', (data) => {
            var json = JSON.parse(data);
            console.log('new user!')
            console.log(json.userid)
            console.log(json.username)
            users.push({ id: json.userid, username: json.username })
        });
        socket.on('chat_new_message', (data) => {
            var json = JSON.parse(data);
            console.log(`${json.userid} - new message!`)
            const user = users.find((user) => user.id === json.userid)
            console.log(json.msg)
            // check whether `user` exit
            if (user) {
               console.log(user.username)
            }