Hitting Digest already called on cryptoJS during unit testing

import crypto from 'crypto';

export const getChecksum: (_: PathLike) => Promise<string> = (path: PathLike) =>
  new Promise(resolve => {
    const hash = crypto.createHash('md5');
    const input = fs.createReadStream(path);

    input.on('data', chunk => {
      hash.update(chunk);
    });

    input.on('close', () => {
      resolve(hash.digest('hex'));
    });
  });

Given the function, it can accept a file path, and perform hash.update while streaming the file, I’m trying to write an unit test like below

describe('getChecksum()', () => {
  afterEach(() => {
    vol.reset();
  });

  it('should generate consistent checksum', async () => {
    vol.fromJSON(
      {
        './some/README.md': '1',
        './some/index.js': '2',
      },
      '/app'
    );

    const result = await getChecksum('/app/some/index.js');
    expect(result).toBe('c81e728d9d4c2f636f067f89cc14862c');
  });
});

From the Unit Test above, assertion was able to perform correctly, however, I’m hitting error below

  ● getChecksum() › should generate consistent checksum

    Error [ERR_CRYPTO_HASH_FINALIZED] [ERR_CRYPTO_HASH_FINALIZED]: Digest already called

      63 |
      64 |     input.on('close', () => {
    > 65 |       resolve(hash.digest('hex'));
         |                    ^
      66 |     });
      67 |   });
      68 |

Not too sure which part has gone wrong?

Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k

I’m tacking this problem and I can’t seem to arrive at the correct solution. The question is:

“Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k. If an integer appears in the list multiple times, each copy is considered to be different; that is, two pairs are considered different if one pair includes at least one array index which the other doesn’t, even if they include the same values.”

My approach is that I’m building a map that contains each number in the array and the number of times it occurs. Then I iterate over the map to find my answer.

function numberOfWays(arr, k) {
  let output = 0;
  let map = {};

  // put values and # of occurences into map
  for(let i = 0; i < arr.length; i++) {
    let key = arr[i];
    if(!(key in map)) {
      map[key] = 1;
    } else {
      map[key]++;
    }
  }
  
  for(let key in map) {
    let difference = k-key
    if((difference) in map) {
      if(k/2 === key) {
        output += map[key]*(map[key]-1)/2;
      } else {
        output += map[key] * map[key] / 2;  // divide by 2 so that pairs aren't counted twice
      }
    }
  }

  return output;
}

The two test cases are:
var arr_1 = [1, 2, 3, 4, 3]; expected result: [2] — I’m getting [3]

var arr_2 = [1, 5, 3, 3, 3]; expected result: [4] — I’m getting [5.5]

I’m definitely doing something wrong in my calculations, but I can’t seem to wrap my ahead around it.

How to extract email addresses from my string result and save them in a txt file one per line

im fetching data from different sources and the output string looks like the following:

"addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main-nordend-west","addressId":"132232","businessEntryCount":1925}],"generated":"2022-01-23 19:35:43.469","grisuLocation":null,"district":null,"geo":null};
                kt.Data.SearchResult.distanceLocation = "Frankfurt am Main";
        kt.Data.SearchResult.distanceStreetnumber = "";
        kt.Service.citySlug = 'frankfurt';
        kt.Data.what = 'Handwerker';
        kt.Data.where = 'Frankfurt am Main';
        kt.Data.trade = 'Maler';
    

                {"@context":"http://schema.org","@type":"SearchResultsPage","mainEntity":{"@type":"ItemList","itemListElement":[{"@type":"ListItem","item":{"@type":"LocalBusiness","name":"Dachdecker Olaf Pocklitz","url":"http://www.test.de","email":"[email protected]","address":{"@type":"PostalAddress","postalCode":"65931","addressLocality":"Frankfurt","addressRegion":"Hessen",

The above string content is my data result. I want to have only all the email adresses left to save them in a file. In the above example it would be [email protected] and if we have more than one email adress, then I want the second email adress in a new line. Im struggling how to perfectly filter them out and afterwards save them one by line. I already made it work to save it but I dont know how to only get the email address out of it:

console.log('received data: ' + data)
fs.writeFileSync('./results/test.json', data)

Generate multiple select inputs with v-for

I am desperately trying to generate multiple select inputs for a given JSON from an Backend but I cant make it work. The JSON response I am getting looks smth like this:

{
    "selectData": [
        {
            "id": "ats_2323680",
            "label": "Follow up",
            "value": "option_id_1"
        },
        {
            "id": "ats_2323701",
            "label": "1st Interview, Client",
            "value": "option_id_1"
        },...
    ],
    "optionData": {
        "texts": [
            "Sourced",
            "On hold",
            ...
        ],
        "values": [
            "option_id_1",
            "option_id_2",
        ]
    }
}

Ive already tried several ways and my last attempt looks like this:

Template:

 <div v-for="select in selectData" :key="select.id">
          <p>{{ select.label }}</p>
          <v-select
            :items="optionData.texts"
            :value="getOptionById(select.value)"
            @input="(id) => updateSelect(select, id)"
          ></v-select>
  </div>

Script:

<script>
export default {
  data() {
    return {
      selectData: [],
      optionData: {
        values: [],
        texts: [],
      },
    };
  },
  methods: {
    fetchData() {
      const headers = this.authorizationHeader;
      axios
        .get(url,
          {
            headers,
          }
        )
        .then((response) => {
          let data = response.data;
          this.selectData = data.selectData;
          this.optionData = data.optionData;
        })
        .catch((error) => console.log(error));
    },
    updateSelect(select, id) {
      select.value = id;
    },
    getOptionById(id) {
      let i = this.optionData.values.findIndex((x) => x === id);
      return this.optionData.texts[i];
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>

I am also not super happy with the JSON struct I am getting. The reason that the optionTextId is also send is, that the optionTexts will be in different languages.
I am really happy with any advise.

Why my carousel doesn’t get down under my sticky navbar?

I decided to add a carousel to my website in the second section (in the middle of the page after the hero), then I try to add a sticky navbar and it’s work correctly except for the carousel shown above the navbar.

here is the code I used for the carousel (I used Bootstrap 5).

<section class="bg-dark text-dark text-center text-sm-start MyContent">
    <div class="bg-light">
        <div class="container" >
            <div class="d-sm-flex align-items-center justify-content-center">

                <!-- carousel -->

                <div class="carousel slide Mycarousel" id="demo" data-bs-ride="carousel">

                    <div class="carousel-indicators">
                        <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>

                        <button type="button" data-bs-target="#demo" data-bs-slide-to="1" aria-label="Slide 2"></button>

                        <button type="button" data-bs-target="#demo" data-bs-slide-to="2" aria-label="Slide 3"></button>

                        <button type="button" data-bs-target="#demo" data-bs-slide-to="3" aria-label="Slide 4"></button>

                        <button type="button" data-bs-target="#demo" data-bs-slide-to="4" aria-label="Slide 5"></button>
                    </div>

                    <div class="carousel-inner">
                        <div class="carousel-item active">
                          <img src="/images/very.jpg" class="d-block width1" alt="...">
                          <div class="carousel-caption d-none d-sm-block">
                            <button class="btn btn-primary" type="button">Very Little Nightmares</button>
                          </div>
                        </div>

                        <div class="carousel-item">
                          <img src="/images/pubg.jpg" class="d-block width1" alt="...">
                          <div class="carousel-caption d-none d-sm-block">
                            <button class="btn btn-primary" type="button">PUBG New-state</button>
                          </div>
                        </div>

                        <div class="carousel-item">
                          <img src="/images/pes.jpg" class="d-block width1" alt="...">
                          <div class="carousel-caption d-none d-sm-block">
                            <button class="btn btn-primary" type="button">PES 2021</button>
                          </div>
                        </div>

                        <div class="carousel-item">
                          <img src="/images/cod.jpg" class="d-block width1" alt="...">
                          <div class="carousel-caption d-none d-sm-block">
                            <button class="btn btn-primary" type="button">COD Mobile</button>
                          </div>
                        </div>

                        <div class="carousel-item">
                          <img src="/images/garena-free-fire-z4-1336x768.jpg" class="d-block width1" alt="...">
                          <div class="carousel-caption d-none d-sm-block">
                            <button class="btn btn-primary" type="button">Free Fire</button>
                          </div>
                        </div>
                    </div>

                    <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="visually-hidden">Previous</span>
                    </button>

                    <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="visually-hidden">Next</span>
                    </button>
                </div>

                <!-- carousel -->

                <div class="divtwo">

                    <h1 id="headerOne1" class="text-warning mx-5 px-1 d-sm-block img-fluid w-50 w-ms-auto">Best <span class="text-info">Games</span> </h1>

                    <p class="lead paragraph mx-5 px-1">Want more amazing games..?</p>

                    <button type="button" class="btn btn1 btn-outline-warning">Recommended</button>
                </div>
            </div>
        </div>
    </div>
</section>

this is the Javascript code I used for my sticky navbar.

window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

I want the form to validate the custom made captcha

I have a set of 10 captcha images in jpg format.All i am remaining to do is to validate if the user input is correct as the captcha text. Below is the complete code for a custom captcha with custom made animated text characters:

Login Page

Captcha System

<span class="navbar-toggler-icon"></span>
<ul class="navbar-nav mr-auto">

  <li class="nav-item active">

    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>

  </li>

  <li class="nav-item">

    <a class="nav-link" href="#">Catogeries</a>

  </li>

  <li class="nav-item dropdown">

    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

      Authors

    </a>

    <div class="dropdown-menu" aria-labelledby="navbarDropdown">

      <a class="dropdown-item" href="#">Blogs</a>

      <a class="dropdown-item" href="#">Development</a>

      <div class="dropdown-divider"></div>

      <a class="dropdown-item" href="#">Business</a>

    </div>

  </li>

  <li class="nav-item">

    <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>

  </li>

</ul>

<form class="form-inline my-2 my-lg-0">

  <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">

  <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>

</form>
<div style="width: 40%; margin: 25px auto;">

<h3 style="text-align: center;">Login Page</h3>

<form method="POST" action="">

  <div class="form-group">

    <label>UserName:</label><input type="text" name="UserName" class="form-control" autofocus placeholder="username">

  </div>

  <div class="form-group">

    <label>Password:</label><input type="Password" name="Password" class="form-control" autofocus placeholder="Password">

  </div>



  <label>Enter Captcha:</label>

  <img src= imageArray  onclick="generateRandomPicture()" width="195" height="100" id="capt">

  <div class="form-row">

    <div class="form-group col-md-6">

   </div>

    <div class="form-group col-md-8">



      <input type="text" class="form-control" id="textinput">

    </div>

  </div>
    <button onclick="validcap()" class="btn btn-lg btn-success btn-block">Submit</button>

  </div>

</form>



<h6>Captcha not visible <img src="refresh.jpg" width="30px" onclick="generateRandomPicture(imageArray)"></h6>

<p>New Here?<a href="">Sign Up</a> </p>

<p>Forgotten Password?<a href="">Recover here</a> </p>

const imageArray = [{

src:”https://lh3.googleusercontent.com/O9OkhSZgJ9P0XTN_w63i9UlT3_pzr703tGPGLpaCmAOte4W4T5vOVqnSUYugMyjLgi39wq0=s170″,name:”MCABJ”},

“https://lh3.googleusercontent.com/k5hld8V0gDuzbXYlROE0TDvCb8lJ-2a1CBT41x6EG50_DW_wtf6ma5uVerWdI-oHDqmTVw=s160”,

“https://lh3.googleusercontent.com/BDW21nm1NoPUV_X33Q8mtHktuqwblbu46_oSWrHmCyW2OBlbR0d0QwYrER8VRXtrhTEBiw=s170”,

“https://lh3.googleusercontent.com/Zr71njboeq8BRXsBkQeegDaBUDGwvpbaDDs7gSST2MEkn00lTo_EvVVdU01w41Ed8NphC5g=s170”,

“https://lh3.googleusercontent.com/eSQry20u69Xr7urTZjXNT31dUVV6xGTsZqRCo1r-bqtQaT_FVJ2m3WNYnxPvidS4lpvG=s170”,

“https://lh3.googleusercontent.com/zbyXqv38dV6A1WZrnXgRr0lLZ0KX4PHK1Yph3t9bndR1zfGrC1LqYpMO8bXkg9R3x1s6VQ=s170”,

“https://lh3.googleusercontent.com/yniDGYeKA7HhOYcmIuc1Yv8TzgFDnIGL4jahYcMaRQ3kvyHpYoUtSKtTkpffZrJRsk5H=s170”,

“https://lh3.googleusercontent.com/6tnVYghNVLC7_rZcf-Gr2cyDGffo3ETZ2wPU_Isj0jkrhIMT7RZyryB1XIT8JpXP_er6DA4=s170”,

“https://lh3.googleusercontent.com/vLacveGYUzwMvjdclxYPvyhc21dG6O4WPujz75DMorawxg8Y8oUY2t4S1n6ATeKpvlU4PZ4=s170”,

“https://lh3.googleusercontent.com/qicMuzLUCIIM35DX0GWEJpqiYBzzjNUdOV3xrB9CCe5K0s5xEua1rgFX7FWJ07zdsd-D=s170”

];

const image = document.querySelector(“img”);

const button = document.querySelector(“button”);

window.onload = () => generateRandomPicture(imageArray);

button.addEventListener(“click”, () => generateRandomPicture(imageArray));

function generateRandomPicture(array){

let randomNum = Math.floor(Math.random() * array.length);

image.setAttribute(“src”, array[randomNum]);

if(image.setAttribute(“src”, array[randomNum])==”https://lh3.googleusercontent.com/O9OkhSZgJ9P0XTN_w63i9UlT3_pzr703tGPGLpaCmAOte4W4T5vOVqnSUYugMyjLgi39wq0=s170″)

stg1=”MCABJ”

}

/*

function validcap(){

var stg2 = document.getElementById(‘textinput’).value;

if(stg1==stg2){

alert(“Form is validated Succesfully”);

return true;

}else{

alert(“Please enter a valid captcha”);

return false;

}

*/

Please tell how can i assign a value to each image and validate by comparing to user input.

Datatable imports messing up other functionalities

Currently I’m using Datatable API to fill up my table with data. Recently I added the Export to Excel using column selectors. For this I imported the following libraries:

<link href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script> 
<script src="https://cdn.datatables.net/select/1.3.4/js/dataTables.select.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.colVis.min.js"></script> 

Now the functionality for the export to excel is working, but now none of my other buttons that I had in that page previously are working. Once I commented these 2 lines, the other buttons started working but then the Export functionality also stopped.

<link href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>

So not sure why this is creating conflicts and not sure how to fix it. Nothing shown in console as well

window.innerWidth not working but works when i turn on inspect

window.innerWidth is not working as should do, I need to show an alert message when the window width is less than 480 but it shows nothing but works when I turn on inspect, and here is my code

function updateMessage() {

    if (window.innerWidth < 480) {
        alert("Hello! I am an alert box!!");
    };

  };

  window.addEventListener("load", updateMessage);
  window.addEventListener("resize", updateMessage);

Vue component not loading in InertiaJS

I’m using InertiaJS to build a Vue3 / Laravel app. When I run my app in the browser it gives me the following error in the console. I’m new to InertiaJS and Vue3 and don’t know why my component doesn’t render.

Uncaught (in promise) TypeError: l is null

web.php

// Home route. 
Route::get('/', [HomeController::class, 'index'])

HomeController.php

public function index()
{
    return Inertia::render('Home');
}

My app.blade.php file which is located under ./resources/views/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>@yield('title') - Gainz</title>
        <meta 
        name="description" 
        content="@yield('description')">
        <meta name="google-site-verification" content="n5lVAknL3NblyWPmFzt3ARrtZbDDLIU-KOwA83NiO5w" />
        <!-- Roboto --> 
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;1,100;1,900&display=swap" rel="stylesheet"> 
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet"> 
        <!-- CSS --> 
        <link rel="stylesheet" href="/css/main.css">

        <!-- Bootstrap --> 
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

        <!-- Font Awesome --> 
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
        <!-- Custom scripts --> 
        <script src="/js/app.js"></script>  
    </head>
    <body onmousedown="handleClick(event)">
        @inertia()
        @yield('scripts')
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    </body>
</html>

webpack.mix.js

const mix = require('laravel-mix');
const path = require('path')

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */
mix .js('resources/js/app.js', 'public/js').vue()
    //.js('resources/js/track.js', 'public/js')
    //.js('resources/js/overview.js', 'public/js')
    //.js('resources/js/feed.js', 'public/js')
    .sass('resources/sass/main.scss', 'public/css');
// @ts-ignore
mix.webpackConfig({
    output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
    resolve: {
      alias: {
        '@': path.resolve('./resources/js'),
      },
      extensions: ['.js', '.vue', '.json'],
    },
    devServer: {
      allowedHosts: 'all',
    },
  });

app.js under ./resources/js/app.js

// @ts-nocheck
require('./bootstrap');
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress'

// Creates the inertia vue app. 
createInertiaApp({
    resolve: (name) => require(`./Pages/${name}`),
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mount(el);
    },
});
// Progress bar. 
InertiaProgress.init()

Finally Home.vue under ./resources/js/Pages/Home.vue

<template>
  <div>Hello world</div>
</template>

JavaScript function returning undefined but both cases are defined

My function returns undefinded but the return value is defined.

function createcode() {
            var clientid = interaction.user.id;
            var sqlsearch = `SELECT COUNT(*) AS count FROM codes WHERE ClientID = '${clientid}'`
            database.query(sqlsearch, code, function(err, rows)  {
                if (err) throw err;
                var count = rows[0].count;
                if(count != 0)
                {
                    var exsitingcode;
                    var getexsitingcode = `SELECT codes, codes AS ecode FROM codes WHERE ClientID = '${clientid}'`;
                    database.query(getexsitingcode, async function(err, rows)  {
                        if (err) throw err;
                        exsitingcode = await rows[0].ecode;
                        console.log(`${interaction.user.username} tried creating a code but already has one: ${exsitingcode}`)
                        return exsitingcode;
                    })
                }
                else
                {
                    var code = Math.random().toString(36).slice(3);
                    var sql = `INSERT INTO codes(codes, ClientID) VALUES ('${code}', '${clientid}')`
                    database.query(sql, function(err)  {
                        if (err) throw err;
                        console.log(`Inserted Code: ${code}`)
                        setTimeout(() => {
                            var sqldelete = `DELETE FROM codes WHERE codes = '${code}'`
                            database.query(sqldelete, function (err) {
                                if (err) throw err;
                                console.log(`Code deleted: ${code}`);
                            })
                        }, 300000); // 5Min
                        console.log("returning code...")
                        return code;
                    })
                }
            })
        }

In both cases it returns undefinded. How can I bypass this?

using mysql & discord.js v13

Integrating socket.io with express is it a good idea?

I’m must say I’m very new to back end development,
I’m currently working on an exercise project of making a fake money poker website. I use Node.js socket.io/express-session/passport
At first, I mainly used express with a HTTP server listening on one port. Like this:

const express = require("express")
const app = express()

app.get('/home',connectEnsureLogin.ensureLoggedIn("/loginPage"),function(req, res) {

 //console.log(req.user.username+": sessionId: "+req.sessionID);
  return res.sendFile( __dirname+"/website/index.html"); 
} 
); 
const PORT = process.env.PORT || 5000; 
app.listen(PORT, () => console.log("Poker site Server started on ${PORT})")

The website wasn’t working very fast. When a client joined a poker table they needed to ask the server every second for new updates on the state of the game so that was a lot of HTTP requests coming into my server. So I decided without much theoretical certitude that it seemed like a good idea: To have the server use socket.io sockets to hand info for clients that are in poker tables, but when they are not in poker tables and are just browsing the site I use a HTTP server to handle their request. Code wise I feel I haven’t really managed to do this correctly. My code with Express, express-session, and passport combined makes sure only to hand information to users authenticated. But since The socket.io servers seem totally separate from all the express code, they don’t share the same authentication functionality as the express code. So I need to somehow link my express and socket.io code so I can check if a client is authenticated before handing him any info via sockets. here is the system I’m currently using I didn’t put all my code but I tried to summarize the essential parts:

const express = require('express');
const app = express();
//i creat the http server that is somehow linked with my express app when this server is listening
//it will call express handling methods.
const http = require('http').Server(app); 
const io = require('socket.io')(http);

const path = require("path");
const passport = require("passport");
const connectEnsureLogin = require('connect-ensure-login');
const AccountInfo = require("./AccountInfo").AcccountInfo;
const expressSession = require('express-session')({
    secret: process.env.SESSION_SECRET,
    resave: false, 
    saveUninitialized: false
  });

//passport setup
passport.use(AccountInfo.createStrategy()); 
passport.serializeUser(AccountInfo.serializeUser()); 
passport.deserializeUser(AccountInfo.deserializeUser());

//body parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//Sessions
app.use(expressSession);

//!!!!here is where I connect socket.io with the sessions i found this in another forum. thanks to
//this code I can access the session that a client is using when their socket connects.
io.use(function(socket, next) {
  expressSession(socket.request, socket.request.res, next);
});

//so when a clients socket connects i save his socket.id to his session.
io.on('connection',function(socket) {
  console.log(`socket.io connected: ${socket.id}`);
  // save socket.io socket in the session
  socket.request.session.socketio = socket.id;
  socket.request.session.save();
});

//once the clients socket is connected directly after the clients sends a HTTP "PUT" request
//and this code answers it.
app.post('/Table/ConnectSocketToTable',Utilities.ensureLoggedIn(),function(req, res)
{
   
    //I retrieve the socket using the socket.id I had saved in the session. 
    let socket = io.sockets.sockets.get(req.session.socketio);

    let player = GetPlayerFromAnyTable(req.user.username);
    if(player==null)//the player can't be in two tables at once 
    {
//since now we are in an express callback, express made sure that the client is indeed
//authenticated with the middle-ware: "Utilities.ensureLoggedIn()" also just before I made sure
//the client is not in another table. So we are good to go we can now link the socket to the table
//and have the client receive all the info about the state of his table
        socket.join("table-"+req.session.passport.table);
        req.user.socket = socket;
        let table = GetTable(req.session.passport.table);
        table.sitPlayer(req.user);
    }
    else
    { 
//the player is already connected so we just update his socket to a new one
        player.requestUnseat=false;
        player.account.socket =io.sockets.sockets.get(req.session.socketio);
    }

    socket.on('chatMessage', function(data,time) {
        socket.to("table-"+req.session.passport.table).emit("chatMessage",req.user.username,data,time);
        console.log(`send chat message : ${data}`);
      });
    socket.on('disconnect', function() {
        GetTable(req.session.passport.table).requestUnsitUsername(req.user.username);
        console.log(req.user.username +" was disconnected so now requesting unsit");
      });

    console.log("the socket of "+req.user.username+" has being connected to table-"+req.session.passport.table);
    return res.sendStatus(200); 
});

So for me, the way I’m doing this seems pretty bad since “app.post(‘/Table/ConnectSocketToTable’…)” and “io.on(‘connection’,…)” are two different request listening functions I feel I should probably just do everything in one.
So should I do all the checks in the “io.on(‘connection’,…)” function and somehow manage to make sure the client is authenticated within the callback of io.on(‘connection’,callback) ?
or should I find a way to make the socket connection happen in the initial HTTP call the client uses to join a table, which is what I initially wanted?
But really I’m kinda lost because I’m telling myself maybe I don’t even need Express anymore and I should just use socket.io for everything. I seem to clearly lack the general understanding that would allow me to know what approach I should be going for so any help is welcome. I started doing this self-made exercise to get into server-side development but also if there is any other recommended exercise to start up with back-end development I’m definitely interested in hearing about it.

Removing specific Item/value from LocalStorage and updating the array

I’m struggling to edit an array stored in LocalStorage. I have prior functions that take the DIVs with their unique ID’s and add them as such: localStorage.setItem(“deleted_items”,JSON.stringify(items));

I then have a click function gets the id of the div and store it in a variable as with this example:

function getChat(input){
    let id = $(input).attr('id');
    console.log("Captured ID = " + id); //Returns 27615035196
}

From this, I then also store the items from LocalStorage in a variable

let hiddenItems = JSON.parse(localStorage.getItem("deleted_items"));

I then want to get the index of that item in the array:

const itemIndex = hiddenItems.indexOf();

And then finally with that index, splice the array to remove the item and update it again. But can’t seem to get the last piece of the puzzle here as my itemIndex is returning as -1

I can’t get the actual number of elements

I’m having a problem returning elements from my object array.

I have a slideshow in which an image (photo of the book) and a text (title of the book) must appear.

For the creation of the slideshow I have no problems because I am using querySelectors as shown in the code below.

The problem lies in showing the images with their titles.

In the first part of the code I have an array of objects that gives me the total number of elements present and based on this I create the slideshow (to create the scroll points and the “container” to contain the images) and then subsequently I call the function myFunction with id argument to return the single element (identified by an id).

What I notice is that the urls with the ids are returned to me, but the url with that id is returned multiple times (so it gets copied) and not just once as expected; I should have only 4 url ​​in total (each with the specific id of the element, since only 4 elements). The same happens when I return the array of objects, it does not return 4 but many more. (Below)

Referring to url1:

…/books/123456

…/books/123456

…/books/135623

…/books/123456

…/books/135623

…/books/123789

…/books/123456

…/books/135623

…/books/123789

…/books/146975

If I click on the arrows of the slideshow I only receive one image, the other images I do not receive.

I have no mistakes.

var slideIndex = 1;


    var outerXmlhttp = new XMLHttpRequest();
    var url = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books";
    outerXmlhttp.onreadystatechange = function () {
      var innerXmlhttp;
      if (this.readyState == 4 && this.status == 200) {
        var allbook = JSON.parse(this.responseText);
        for (var i = 0, len = allbook.Items.length; i < len; i++) {
          id = allbook.Items[i].id
          document.querySelector('.slideshow-container').innerHTML += `
          <div class="mySlides fade">
            <div class="numbertext">${i+1}/${allbook.Items.length}</div>
            <img id="img" src onerror="this.onerror=null; this.src=myFunction(${id});" style="width:100%">
            <div class="text" id="title" onclick="myFunction(${id})"></div>
          </div>`;
          document.querySelector('#punt').innerHTML += `
          <span class="dot" onclick=currentSlide(${i+1})></span>`;
          showSlides(slideIndex);
          myFunction(id);
        }
      }
    };
    outerXmlhttp.open("GET", url, true);
    outerXmlhttp.send();

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides fade");
      var dots = document.getElementsByClassName("dot");
      if (n > slides.length) { slideIndex = 1 }
      if (n < 1) { slideIndex = slides.length }
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex - 1].style.display = "block";
      dots[slideIndex - 1].className += " active";
    }

    function myFunction(id) {
      var url1 = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books/" + id;
      innerXmlhttp = new XMLHttpRequest();
      innerXmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          document.getElementById("img").src = "book_img/" + myArr.Item.immagine;
          document.getElementById("title").innerHTML = `<a href="fragmentProva.html?id=${id}">${myArr.Item.titolo}</a>`;
        }
      };
      innerXmlhttp.open("GET", url1, true);
      innerXmlhttp.send();
    }
<div class="slideshow-container" id="slideshow">
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>

  <br>

  <div id="punt" style="text-align:center">
  </div>