What steps can be taken to reset the redis database when the nodejs server disconnects?

I have created a basic chatroom application using a node express server. This application relies on a redis database for storing the nicknames of all connected clients.

Now, I am looking to implement a feature that clears the redis SET named members when the server is closed or disconnected. The code snippet to achieve this is as follows:

redisClient.del("members", function(err, reply){
    console.log("members set delete :" + reply);
});

However, I am unsure about where to place this code and how to handle the final event triggered by the server upon disconnection from the server side.

Server-side code - chatroom.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');
var redisClient = redis.createClient();

io.on('connection', function(client){
    console.log("client connected...");
});

io.on('connection', function(client){
    client.on('join', function(name){
        client.nickname = name;
        // Adding names
        client.broadcast.emit("add member", name);
        redisClient.smembers('members', function(err, names) {
            names.forEach(function(name){   
                client.emit('add member', name);    
            }); 
        });
        client.emit('add member', client.nickname)
        redisClient.sadd("members", name);
    });

    // Remove clients on disconnect
    client.on('disconnect', function(name){
        client.broadcast.emit("remove member", client.nickname);
        redisClient.srem("members", client.nickname);   
    });
});

app.get('/', function(req, res){
    res.sendFile(__dirname + '/views/index.html');
});
server.listen(8080);

Client-side code - views/index.html

<html>
    <head>
        <title>Socket.io Client</title>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    </head>
    <body>
        <h2>Chat box</h2><br>
        <h4 id="status"></h4><br>
        <div>
            <h3>Active members</h3>
            <ul id="members"></ul>
        </div>

        <script>
            var socket = io.connect('http://localhost:8080');

            socket.on('connect', function(data){
                nickname = prompt("What is your nickname?");
                $('#status').html('Connected to Chat Room as \''+nickname+'\'.');        
                socket.emit('join', nickname);
            });

            socket.on('add member', function(name) {
                var member = $('<li>'+name+'</li>').data('name', name);
                $('#members').append(member);   
            });

            socket.on('remove member', function(name) {
                $('#members li').filter(function() { return $.text([this]) === name; }).remove();   
            });

            socket.on('disconnect', function(data){
                $('#status').html('Chatroom Server Down!');        
            });
        </script>
    </body>
</html>

How can I clear the redis database set when my nodejs server disconnects?

Answer №1

If you encounter any issues, make sure to handle the error and end events on the redisClient by referring to the official Redis Package Documentation

redisClient.on("error", function (err) {
      console.log("Error " + err)
      // Your logic for error handling goes here
});

It is advisable to perform necessary actions such as deletion upon initial connection establishment with Redis and also during reconnection instances to maintain a stable connection.

Answer №2

When a socket.io connection is terminated, an event called disconnect will be triggered. Make sure to set up your reset logic within that callback function.

io.sockets.on('connection', function (socket) {
  socket.on('disconnect', function () {
    redisClient.del("members", function(err, reply){
    console.log("Deleting members set :" + reply);
    });
  });
});

Source : How can I handle the Close event in Socket.io?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

What are the ways to recognize various styles of handlebar designs?

Within my project, I have multiple html files serving as templates for various email messages such as email verification and password reset. I am looking to precompile these templates so that they can be easily utilized in the appropriate situations. For ...

Derby.js: organizing client-side code into separate files

I'm attempting to break up some client-side code into separate files within a Derby.js project. This code must remain client-side as it interacts with the TinyMCE editor. My initial attempt was: app.ready(function(model) { var tiny = derby.use(re ...

The route parameters in a Node.js Express app do not support the use of the

In my Node.js 16.18.x application, I have the following code running: app.get('/CheckPlan', (req, res) => { res.setHeader('Content-Type', 'application/json'); var dataToSend; console.log("1111", req. ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

Utilize JavaScript or jQuery to segment HTML elements

Looking for a front-end solution to a common practice. In the past, I've stored reusable HTML elements (such as <nav>, <header>, <footer>, etc.) in a functions.php file and used PHP functions to include them on multiple pages. This ...

Updating the query parameters/URL in Node.js's request module

In my Express.js application, I am utilizing the npm request module to interact with an internal API. The options passed to the request function are as follows: requestOptions = { url : http://whatever.com/locations/ method : "GET", json : {}, qs : { ...

Can you explain the purpose of having module.exports = function(app)?

Can you clarify the significance of the following codes? I would appreciate an explanation for all three lines. module.exports = function(app){ var x = express.router(); var y = express.router(); } I have tried researching these codes online, ...

Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router. In my server.js file, I have the following setup: app.use('/user/:id/profile', require('./routes/profile')); Within my ./routes/profile.js fil ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

What is the best way to showcase the organized values according to their attributes?

How can I sort and display values based on their properties? For example, I want to only show the likes and convert them back into an object so I can use them as properties. I apologize for the previous edit, this is the updated version with a working sim ...

Tips for executing a .exe file in stealth mode using JavaScript?

I am currently working on the transition of my vb.net application to JavaScript and I am facing a challenge. I need to find a way to execute an .exe file in hidden mode using JS. Below is the snippet from my vb.net code: Dim p As Process = New Pro ...

An issue has arisen regarding the type definition for the random-string module

I am currently working on creating a .d.ts file for random-string. Here is the code I have so far: declare module "random-string" { export function randomString(opts?: Object): string; } When I try to import the module using: import randomString = ...

I am currently experiencing issues with the app post feature as it is failing to generate any output

var express = require("express"); var app = express(); var bodyParser = require('body-parser'); var port = 3000; const fs = require('fs'); // establishing connection to MongoDB using Mongoose var mongoose = require("mongoose"); // Imp ...

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

Encountering a JSON error while attempting to install vue/cli using npm

After running npm i -g @vue/cli, I am seeing several warnings. How can I go about investigating and resolving this issue? npm WARN deprecated @hapi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3999c9ab3c2c6ddc2ddc2">[em ...

How can we implement intricate looping mechanisms in hogan js?

Currently, I am in the process of familiarizing myself with expressjs. In my journey to learn this technology, I have encountered a controller that performs queries on a database and returns a JSON object with certain key-value pairs. An example of such an ...

writeFileSync does not generate or add data to file

I currently have multiple SSG pages in my Next.js project and I am working on creating the navigation menu with various routes. I want to optimize this process by "caching" the first API call and retrieving the saved data from a file for subsequent request ...