Uncaught ReferenceError: require is not defined in nodeJs

I know that there are many questions already with this error message, but I have tried all of them and it doesn’t work for me.

I want to use websockets to create a server to build an online multiplayer game (so in browser). I know that socket.io can be used
I have two tutorials that I would like to follow : https://github.com/hnasr/javascript_playground/tree/master/websocket-cell-game and https://github.com/HungryTurtleCode/multiplayerSnake
They are using express and http for the first one and socket.io for the second, but whatever I do I get this error : Uncaught ReferenceError: require is not defined. I mostly tried the solutions in this link : Client on Node.js: Uncaught ReferenceError: require is not defined but without any success. I would like to try the solution using by Peter Mortensen but I don’t know how it should be done.

It has been a week since I am on this error and I still didn’t find a solution that works for me. I wanted to try import but the examples I followed they are using import as follows:

    import { createServer } from "http";
    import { Server } from "socket.io";

But I get the error : "http". Relative references must start with either "/", "./", or "../"
I can solve the socket.io by using this link : https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.js instead of “socket.io”, but I didn’t find it for http.
I tried with another link (https://cdnjs.cloudflare.com/ajax/libs/http-client/4.3.1/http-client.min.js) but it gave me another error so I guess it wasn’t the good way to solve it.

I also tried requirejs but to use it also uses require so it doesn’t work as well (cf this link : https://gist.github.com/guerrerocarlos/3651490)

I don’t know what more I can do…

Here is the last version of my trials

in my index.php :

<script data-main="scripts/main" src="scripts/require.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.js" integrity="sha512-9mpsATI0KClwt+xVZfbcf2lJ8IFBAwsubJ6mI3rtULwyM3fBmQFzj0It4tGqxLOGQwGfJdk/G+fANnxfq9/cew==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="js/serverGame.js"></script>

Here is my serverGame.js

const io = require('socket.io')();

io.on ('connection', client => {
  client.emit('init', {data: 'hello world'})
})

io.listen(3000);

And here is my package.json :

{
  "type": "commonjs",
  "devDependencies": {
    "autoprefixer": "^10.4.7",
    "postcss": "^8.4.14",
    "tailwindcss": "^3.1.2"
  },
  "dependencies": {
    "colyseus.js": "^0.14.13",
    "moment": "^2.29.3",
    "requirejs": "^2.3.6",
    "socket.io": "^4.5.1",
    "ws": "^8.8.0",
    "ws-browser": "^11.4.8"
  },
  "optionalDependencies": {
    "bufferutil": "^4.0.6",
    "utf-8-validate": "^5.0.9"
  }
}

Does anyone have an idea on how to solve my problem ?
Thank you in advance

Kotlin/JS jsRun gives error “[webpack-cli] TypeError: cli.isMultipleCompiler is not a function”

I have a Kotlin multiplatform project with JVM and JS. When executing jsRun gradle task to start the webpack server, it fails with the following error:

Waiting for changes to input files of tasks... (ctrl-d then enter to exit)
[webpack-cli] TypeError: cli.isMultipleCompiler is not a function
[webpack-cli] TypeError: cli.isMultipleCompiler is not a function
    at Command.<anonymous> (C:[email protected]:146:35)
    at async Promise.all (index 1)
    at async Command.<anonymous> (C:MyProjectbuildjsnode_moduleswebpack-clilibwebpack-cli.js:1687:7)

Compilation succeeds and I can serve the project via Ktor, the problem seems to be the webpack dev server.

The package.json that kotlin gradle plugin generates seems to use webpack-cli 4.9.0.

{
  "name": "MyProject-client",
  "version": "1.0.0",
  "main": "kotlin/MyProject-client.js",
  "devDependencies": {
    "sass-loader": "13.0.0",
    "sass": "1.53.0",
    "style-loader": "3.3.1",
    "css-loader": "6.7.1",
    "resolve-url-loader": "5.0.0",
    "webpack": "5.57.1",
    "webpack-cli": "4.9.0",
    "format-util": "1.0.5",
    "source-map-loader": "3.0.0",
    "webpack-dev-server": "4.3.1",
    "dukat": "0.5.8-rc.4"
  },
  "dependencies": {},
  "peerDependencies": {},
  "optionalDependencies": {},
  "bundledDependencies": []
}

This says that it’s a bug in webpack-cli 4.9.0 and suggests upgrading to 4.10.0. I don’t know if/how webpack versions can be changed in Kotlin/JS.

How can I avoid that a select option is being clicked after a specifc requirement?

As you can see down there I am trying to make Select Option with time. But I want don’t want to allow when someone selected maybe 10:00 o’clock that he/she can also select at teh other Select Option 10:00 o’clock or earlier is there a way to fix this with Javascript?

<div class="pop" id="pop1">
    <div class="popinner">
        <h3>Normale Büros</h3>
        <p>Start Uhrzeit:</p>
        <select name="Urhzeit" id="time1" type="submit">
          <option value="t1">08:00</option>
          <option value="t2">09:00</option>
          <option value="t3">10:00</option>
          <option value="t4">11:00</option>
          <option value="t5">12:00</option>
          <option value="t6">13:00</option>
          <option value="t7">14:00</option>
          <option value="t8">15:00</option>
          <option value="t8">16:00</option>
        </select>
        <p>End Uhrzeit:</p>
        <select name="Urhzeit" id="time2" type="submit">
          <option value="t1">09:00</option>
          <option value="t2">10:00</option>
          <option value="t3">11:00</option>
          <option value="t4">12:00</option>
          <option value="t5">13:00</option>
          <option value="t6">14:00</option>
          <option value="t7">15:00</option>
          <option value="t8">16:00</option>
          <option value="t8">17:00</option>
        </select>
     </div>
     <button type="button" onclick="normalesBuchen()" class="btnpop1" href="#">Buchen</button>

How can I record response time to a video in Qualtrics using keypress and autoadvancing to next question

Hi all and thanks for reading. I am new to JS and Qualtrics and want to record the response time to a video being played. (For context subjects will be responding to a video of a driving situation and using the enter/return button to respond). I want to be able to record response time for each video. I could use the timing question but that begins the timer from the moment the page loads, I want to record it from the start of the video playing. This is the code I currently have in which enables fullscreen and allows me to press the enter button to then auto advance to the next question. What and where should I add code to capture response time to each video? Any help would be great.

Qualtrics.SurveyEngine.addOnload(function() {
var qid = this.questionId;
document.onkeydown = function(event) {
    console.log('keydown',event);
    if (event.which == 13) {
        event.preventDefault();
        jQuery('#NextButton').click();
        }
    }
var qobj = this;
qobj.hideNextButton();
jQuery("#clip1").on("ended", function() { qobj.clickNextButton() });
});

var element = document.querySelector("#clip1");


element.requestFullscreen()
    .then(function() {

})

How to convert PHP MD5 in NodeJS

I couldn’t find a concrete example for my problem

I need to convert this line PHP in NodeJS :

if (md5($value1.$value2.$value3.$value4.$value5) != $value)

I have used several things without success, like CryptoJS.HmacMD5, CryptoJS.MD5 or md5

I feel it’s a bit more complex with NodeJS, the values ​​correspond to queries in the url that I retrieve with express, req.query.value_1 …

Get variable of PrimeFaces Component Function

I have a range DatePicker from Primefaces.
But I also want to be able to just select one date.

But if i do so, i won’t get any values, just a empty array.
This is because the internal function (which i can’t modify) only returns something when two values are given. Or at least I think that.

The workaround which i thought of was just taking the first value of the array by calling it with a javascript function, but i can’t access it, because the PF function has neither a function name nor a class.

Here the code of the PrimeFaces function:

 if (this.isRangeSelection()) {
                                if (this.value && this.value.length) {
                                    var b = this.value[0],
                                        g = this.value[1];
                                    d = this.formatDateTime(b);
                                    if (g) {
                                        d += " " + this.options.rangeSeparator + " " + this.formatDateTime(g)
                                    }
                                }
                            }

Here is my poor javascript attempt:

<script type="text/javascript">
    function getArrayValue(){
        console.log("inFunction");
        console.log(window.d.value[0]);
    }
    </script>

This is called with this:

<div class="p-field p-col-12 p-md-4">
    <p:datePicker id="range" selectionMode="range"
            value="#{SearchBean.range}" onblur="getArrayValue()">
    </p:datePicker>
 </div>

Thanks for your help in advance! 🙂

Toggle body class through Helmet

I’m trying to create an image overlay with no scroll, and I therefore need to style the body when my li is active. I’m trying to do this through Helmet, but it’s not working. It just says <body class=""> in the browser.

The component:

import React, { useState } from "react"
import { Helmet } from "react-helmet"

export default function ToggleActive({ children, size }) {
  const [isActive, setActive] = useState("false")

  const handleToggle = () => {
    setActive(!isActive)
  }

  return (
    <li className={isActive ? size : "active"} onClick={handleToggle}>
      <Helmet>
        <body className={isActive ? null : "no-scroll"} />
      </Helmet>
      {children}
      <button onClick={handleToggle} />
    </li>
  )
}

What’s wrong here?

JavaScript Complex Object / Array Destructuring [duplicate]

I have an object like below. In that I need to remove the particular section only. Someone can help on this?

I need to remove this based on some condition. Please provide some suggestions on this.

Can we use single line array destructuring option or any other solutions?

The only unique identifier here is “menuKey”: “sidebarRewards”

Needs to be removed part:

{
          "menuKey": "sidebarRewards",
          "label": "Smart Rewards",
          "iconSetName": "narrow",
          "description": "",
          "url": "example.com/account/sidebar/index.tmpl#rewards"
        }

Original Object:

{
  "profile-welcome": {
    "type": "user-profile-welcome",
    "params": {
      "welcomeBack": "Welcome Back!"
    }
  },
  "sidebar-tier": {
    "type": "user-sidebar-tier",
    "params": {
      "rewardsLink": {
        "label": "REWARDS",
        "url": "/smartrewards"
      }
    }
  },
  "account-links": {
    "type": "account-links",
    "params": {
      "menu": [
        {
          "menuKey": "sidebarAccount",
          "label": "My Account",
          "iconSetName": "narrow",
          "description": "",
          "url": "example.com/account/index.tmpl"
        },
        {
          "menuKey": "sidebarSettings",
          "label": "Account Settings",
          "iconSetName": "narrow",
          "description": "",
          "url": "example.com/account/profile_preferences.tmpl"
        },
        {
          "menuKey": "sidebarRewards",
          "label": "Smart Rewards",
          "iconSetName": "narrow",
          "description": "",
          "url": "example.com/account/sidebar/index.tmpl#rewards"
        },
        {
          "menuKey": "sidebarSignOut",
          "label": "Sign Out ",
          "iconSetName": "narrow",
          "description": "",
          "url": "example.com/account/signin.tmpl?_SUBMIT=signout"
        }
      ]
    }
  },
  "showcase": {
    "type": "showcase",
    "params": {
      "brandServices": {
        "header": "SKIN SERVICES",
        "infoLink": {
          "label": "",
          "url": ""
        },
        "list": [
          {
            "showCaseKey": "firstBrandShowcase",
            "title": "Skin Services.",
            "teaser": "Our team of Consultants is at your fingertips for tips and advice.",
            "label": "See All Skin Services",
            "url": "/services"
          },
          {
            "showCaseKey": "secondBrandShowcase",
            "title": "Try on makeup.",
            "teaser": "Find your perfect shades and use your phone to try them on.",
            "label": "Select Makeup to Try On",
            "url": "/clinicalreality"
          }
        ]
      }
    }
  }
}

How to call setState without any triggering events?

I want to update the value of a counter variable after some fixed time indefinitely. Here is my code:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      myCount: 1    
    };
  }
  
  // Update state after every 15 seconds.
  setTimeout(function(){
     this.setState({myCount: this.state.myCount + 1});
  }, 15000);
}


However, I get error about unexpected token with this component. How can I set state within the class properly without using any event listeners?

Thanks.

How to Disable some Date’s for Long Events in Full Calendar

We Display Classes (Music, Language,..) in Full Calendar plugin. Class Duration is 3 months. We need to hide holidays dates in Calendar view. my code below.

"events": [
    {
      "title": "selected dates Events",
      "allDay": false,
      "start": "2022-06-16T15:03:00",
      "unformated_date": "June 16, 2022",
      "url": "http://localhost:8888/boxingstudio/product/selected-dates-events/",
      "post_id": 536,
      "multi_day": "selected",
      "color": "#16a75d",
      "textColor": "#ffffff",
      "in_stock": "yes"
    },
    {
      "title": "selected dates Events",
      "allDay": false,
      "start": "2022-06-23T15:03:00",
      "unformated_date": "",
      "url": "http://localhost:8888/boxingstudio/product/selected-dates-events/",
      "post_id": 536,
      "multi_day": "selected",
      "color": "#16a75d",
      "textColor": "#ffffff",
      "in_stock": "yes"
    },
    {
      "title": "selected dates Events",
      "allDay": false,
      "start": "2022-06-25T15:03:00",
      "unformated_date": "June 25, 2022",
      "url": "http://localhost:8888/boxingstudio/product/selected-dates-events/",
      "post_id": 536,
      "multi_day": "selected",
      "color": "#16a75d",
      "textColor": "#ffffff",
      "in_stock": "yes"
    },
    {
      "title": "selected dates Events",
      "allDay": false,
      "start": "2022-06-26T15:03:00",
      "unformated_date": "June 26, 2022",
      "url": "http://localhost:8888/boxingstudio/product/selected-dates-events/",
      "post_id": 536,
      "multi_day": "selected",
      "color": "#16a75d",
      "textColor": "#ffffff",
      "in_stock": "yes"
    },
    {
      "title": "selected dates Events",
      "allDay": false,
      "start": "2022-06-29T15:03:00",
      "unformated_date": "June 29, 2022",
      "url": "http://localhost:8888/boxingstudio/product/selected-dates-events/",
      "post_id": 536,
      "multi_day": "selected",
      "color": "#16a75d",
      "textColor": "#ffffff",
      "in_stock": "yes"
    },
    {
      "title": "New Kick Boxing Product 1233",
      "allDay": false,
      "start": "2022-06-23T00:00:00",
      "unformated_date": "June 23, 2022",
      "url": "http://localhost:8888/boxingstudio/product/new-kick-boxing-product-1233/",
      "post_id": 535,
      "color": "#16a75d",
      "textColor": "#ffffff",
      "end": "2024-04-19T00:00:00",
      "unformated_end_date": "April 19, 2024",
      "in_stock": "yes"
    },
    {
      "title": "Kick Boxing Test",
      "allDay": false,
      "start": "2022-06-20T03:02:00",
      "unformated_date": "June 20, 2022",
      "url": "http://localhost:8888/boxingstudio/product/kick-boxing-test/",
      "post_id": 531,
      "color": "#16a75d",
      "textColor": "#ffffff",
      "end": "2022-07-18T14:02:00",
      "unformated_end_date": "July 18, 2022",
      "in_stock": "yes"
    }
  ]

`import.meta.hot.accept()` a Svelte component dependency?

Is it possible to import.meta.hot.accept() a Svelte component dependency? I’d like to update things in the parent component when the child component is changed.

This quick experiment shows dependent modules can be accepted via the Vite HMR API, but not Svelte modules. The callback for the vanilla JS module is called, but not the callback for the Svelte module:

<script>
  import js from './js.js'
  import Svelte from './Svelte.svelte';

  if (import.meta.hot) {
    import.meta.hot.accept('./js.js', () => {
      console.log('hot.accept js.js');
    })

    import.meta.hot.accept('./Svelte.svelte', () => {
      console.log('hot.accept Svelte.svelte');
    })
  }
</script>

Dev console output:

## Update js.js file:
hot.accept js.js
[vite] hot updated: /src/js.js via /src/App.svelte
## Update  Svelte.svelte file:
[vite] hot updated: /src/Svelte.svelte

I think either the ID for the Svelte module is different, or the callback is being ignored/over-ridden by svelte-hmr.

Onclick is only triggered once after assigning functions through for loop

In those for loop, I am assigning a function to a close button that will essentially remove a mark tag from some text.

    for (q = 0; q < json_response.trainer.annotation.length; q++) {
        let close_ = document.getElementById(`cl_${x3}_${q}`);
        console.log(close_)
        close_.onclick = function () {
            delete_ent(this);
        };
    };


function delete_ent($this) {
    let all_text = $this.parentNode.parentNode.innerHTML;
    console.log($this, $this.parentNode);
    let test1 = $this.parentNode.innerHTML;
    let replace_text = test1.split("<span>");
    // console.log(replace_text[0]);
    let updated_text = all_text.replace(`${$this.parentNode.outerHTML}`, `${replace_text[0]}`);
    $this.parentNode.parentNode.innerHTML = updated_text;
}

It works exactly as intended for the first mark tag removed, but then after it’s updated the text, the other close buttons stop working.

This is for a chrome extension