electron-forge import error: npm does not support Node.js v22.14.0

I followed electron’s tutrial steps described at:
https://www.electronjs.org/ja/docs/latest/tutorial/tutorial-packaging

The problem is electron-forge import command has failed as follows:

D:WORKJavaScriptnodeelectronmy-electron-app>node -v
v22.14.0

D:WORKJavaScriptnodeelectronmy-electron-app>npm -v
11.2.0

D:WORKJavaScriptnodeelectronmy-electron-app>npx -v
11.2.0

D:WORKJavaScriptnodeelectronmy-electron-app>fnm --version
fnm 1.38.1

D:WORKJavaScriptnodeelectronmy-electron-app>npx electron-forge import
√ Checking your system
√ Locating importable project
> Processing configuration and dependencies
  √ Resolving package manager: npm
  × Installing dependencies
    › Failed to install modules: ["electron-squirrel-startup"]

    With output: Command failed with a non-zero return code (1):
    npm install electron-squirrel-startup

    npm WARN npm npm does not support Node.js v22.14.0
    npm WARN npm You should probably upgrade to a newer version of node as we
    npm WARN npm can't make any promises that npm will work with this version.
    npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11, 12.
    npm WARN npm You can find the latest version at https://nodejs.org/
    npm ERR! cb.apply is not a function
...

Environment Info:

  • OS: Windows 10 64bit
  • node: 22.14.0
  • npm: 11.2.0
  • fnm: 1.38.1

installed npm packages:

  "devDependencies": {
    "@electron-forge/cli": "^7.8.0",
    "electron": "^35.0.3"
  },
  "dependencies": {}

I uninstalled old version of Node and installed Node.js v22 LTS following the Node.js web site:

# Download and install fnm:
winget install Schniz.fnm

# Download and install Node.js:
fnm install 22

# Verify the Node.js version:
node -v # Should print "v22.14.0".

# Verify npm version:
npm -v # Should print "10.9.2".

Then I updated npm 10.9.2 to 11.2.0 because the error message suggests
installed npm is too old.

npm -g update npm

I also tried to delete all of globally installed npm packages,
but the result is the same.

How to save image from front camera with input file type capture camera

I want to create a web application with a feature to take pictures from the front camera with html tag such as

  • html
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" capture="camera" accept="image/*" class="btn btn-primary" 
       id="takePhoto" name="takePhoto" />
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Upload!" />
</form>

  • Javascript
       <script>
    
        $(document).ready(function(){
           $("form#data").submit(function(e) {
               e.preventDefault();    
               var formData = new FormData(this);

               $.ajax({
                  url:'https://example.com/proccess.php',
                  crossDomain: true,
                  type: 'POST',
                  data: formData,
                  success: function (data) {
                     alert(data)
                  },
                  cache: false,
                  contentType: false,
                  processData: false
               });
            });
        });
     </script>

  • php

….

            header("Access-Control-Allow-Origin: *");
            header('Access-Control-Allow-Methods: GET, POST, REQUEST');
     
            $folderPath = "uploads/";
        $tdate = date('d_m_Y_h_i_s');       
        $allowed_ext = array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'rar', 'zip', 'jpg', 'jpeg', 'png');
        $file_name = $_FILES["takePhoto"]["name"];
        $file_temp = $_FILES["takePhoto"]["tmp_name"];
        $sourceProperties = getimagesize($file_temp);
             
             $fileNewName = $tdate;
             $ext = pathinfo($_FILES["takePhoto"]["name"], PATHINFO_EXTENSION);
             $getname = explode(".", $file_name);
         
             $ori_file = substr(str_replace(str_split('\/:*#?"<>|&+-;.()'), '_', $getname[0]),0);
             $ori_file = str_replace(" ","_",$ori_file);
         
             $file_name_exp = explode(".", $file_name);
         $file_ext = strtolower(array_pop($file_name_exp));
                = strtolower(end(explode('.', $file_name)));
         $file_size = $_FILES["takePhoto"]['size'];
         
             $file_name_up = $ori_file.'_'.$tdate.'.'.$file_ext;
                                
         if(in_array($file_ext, $allowed_ext) === true){
        
           $local = 'uploads/'.$file_name_up;
         
                  if (move_uploaded_file($file_tmp,$local)) {
                      echo "The file ". basename( $file_name_up) . " has been uploaded.<br>";
          
                        
                      if(rename($local, "/mnt/drive/server/uploads/".basename( $file_name_up))) {
                          echo "File moving operation success<br/>"; 
                       }
                       
                  } else {
                       echo "";
                  }
                            
         }else{
         echo '<div class="error">ERROR: Extentions not available!</div>';
         }              

If using the smartphone’s rear camera, the image can be saved, but if using the front camera, the image cannot be saved perfectly, whether because of the resolution or other things.

Javascript numeric as string

The following javascript switch statement returns the default value when grape.abv = ’10-11.5%’ or any on the use cases with numeric looking formulas. Only the over and under cases work. I cannot figure out how to force it to evaluate them as strings instead I think it is attempting numeric subtraction or something like that…..

I tried adding a space to the incoming value and all of the cases to force them as strings but that did not work either…..

   switch(String(grape.abv)) {
        case String('Under 10%'):
            grape.abv = 1;
            break;
        case String('10-11.5%'):
            grape.abv = 2;
            break;
        case String('11.5-13.5%'):
            grape.abv = 3;
            break;
        case String('13.5-15%'):
            grape.abv = 4;
            break;
        case String('Over 15%'):
            grape.abv = 5;
            break;
        default:
            grape.abv = null;
    }

Webside JavaScript – Trouble with changing class and text inside try/catch statement in function [duplicate]

So, I’m currently having a lot of trouble trying to change the text and color of a certain element. Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="icon" type="image/x-icon" href="favicon_sent.ico">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="https://smtpjs.com/v3/smtp.js"></script>
        <title>Email Sent!</title>
    </head>
    <body>
        <p id="status" class="thinking">Processing...</p>
        <script type="text/javascript">
            st = document.getElementById("status");
            responses = {
                "undefined": "Processing...",
                "success": "Success!",
                "failure": "Uh-Oh! Something went wrong."
            }
            classes = {
                "undefined": "thinking",
                "success": "success",
                "failure": "failure"
            }
            s = "undefined";
            var r;
            function sendEmail() {
                try {
                    Email.send({
                        Host: "smtp.gmail.com",
                        Username: "sender@email_address.com",
                        Password: "Enter your password",
                        To: 'receiver@email_address.com',
                        From: "sender@email_address.com",
                        Subject: "Sending Email using javascript",
                        Body: "Well that was easy!!"
                    })
                        .then(function (message) {
                            r = "success";
                        });
                } catch (err) {
                    var r = "failure";
                }
                return r;
            }
            s = sendEmail();
            st.setAttribute('class',classes[s]);
            st.innerHTML = responses[s];
        </script>
    </body>
</html>

I’m trying to change the text and class of p#status.thinking, but nothing’s happening. I found out the problem is with the return. Your help is greatly appreciated.

P.S. There are no errors in the console.
P.P.S. I’m writing this in an online HTML compiler (see here), which is not by my organization.

Chrome Extension – Service worker registration failed. Status code: 3

Have you guys encountered the problem that background js is not loaded into the extension?

Returns an error
Service worker registration failed. Status code: 3
in this line

background": {
      "service_worker": "background.js", 
      "type": "module"
    },

background.js

  import { initAuth } from "./logic/auth";
    import { startParser } from "./logic/start";
    
    chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
      try {
        if (message.action === "AUTH_REQUEST") {
          const success = await initAuth();
          sendResponse({ success });
        }
        if (message.action === "START_PARSER") {
          await startParser(message.profiles);
          sendResponse({ success: true });
        }
      } catch (error: unknown) {
        console.error("Error in background script:", error);
        sendResponse({ success: false, error });
      }
      return true;
    });


manifest.json
{
    "manifest_version": 3,
    "name": "My Extension (Dev)",
    "version": "0.0.1",
    "description": "Development version of my extension",
    "permissions": [
      "storage",
      "activeTab",
      "scripting"
    ],
    "host_permissions": [
      "https://*/*",
      "http://*/*"
    ],
    "background": {
      "service_worker": "background.js", 
      "type": "module"
    },
    "action": {
      "default_popup": "./ui/popup.html"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"],
        "run_at": "document_idle"
      }
    ]
  }

Webside JavaScript – Trouble with changing class and text inside try/catch statement in function

So, I’m currently having a lot of trouble trying to change the text and color of a certain element. Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="icon" type="image/x-icon" href="favicon_sent.ico">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="https://smtpjs.com/v3/smtp.js"></script>
        <title>Email Sent!</title>
    </head>
    <body>
        <p id="status" class="thinking">Processing...</p>
        <script type="text/javascript">
            st = document.getElementById("status");
            responses = {
                "undefined": "Processing...",
                "success": "Success!",
                "failure": "Uh-Oh! Something went wrong."
            }
            classes = {
                "undefined": "thinking",
                "success": "success",
                "failure": "failure"
            }
            s = "undefined";
            var r;
            function sendEmail() {
                try {
                    Email.send({
                        Host: "smtp.gmail.com",
                        Username: "sender@email_address.com",
                        Password: "Enter your password",
                        To: 'receiver@email_address.com',
                        From: "sender@email_address.com",
                        Subject: "Sending Email using javascript",
                        Body: "Well that was easy!!"
                    })
                        .then(function (message) {
                            r = "success";
                        });
                } catch (err) {
                    var r = "failure";
                }
                return r;
            }
            s = sendEmail();
            st.setAttribute('class',classes[s]);
            st.innerHTML = responses[s];
        </script>
    </body>
</html>

I’m trying to change the text and class of p#status.thinking, but nothing’s happening. I found out the problem is with the return. Your help is greatly appreciated.

P.S. There are no errors in the console.
P.P.S. I’m writing this in an online HTML compiler (see here), which is not by my organization.

Javascript/Typescript Issue with ipc serialization of an object containing multiple uint8array types; how to deserialize transfered object?

An app architecture decision was made to fork processes to achieve high-load, non-blocking transaction updates. Now, we’re contending with ipc serialization ‘challenges’ that stem from the serialization of Uint8Array(3) {fixed-length} primary keys into node.js { type: ‘Buffer’, data: [255, 255, 255] } as an example.

The data model uses pk keys in uin8array form primarily for access to the database. The question: is there a way to prevent deserialization or a fast, efficient, or better way to preserve or return structures received over ipc to their native form?

The following samples show this condition:

Data Sent

sent: {
  instrument: <Buffer cb 42 a5>,
  symbol: 'XRP-USDT',
  base_currency: <Buffer b5 cd b2>,
  base_symbol: 'XRP',
  quote_currency: <Buffer 35 0f e2>,
  quote_symbol: 'USDT',
  period: <Buffer ca 34 49>,
  timeframe: '15m',
  timeframe_units: 15,
  bulk_collection_rate: 1440,
  interval_collection_rate: 4,
  sma_factor: 60,
  digits: 5,
  trade_state: <Buffer 7c 7a b8>,
  state: 'Enabled',
  active_collection: 1,
  suspense: 0
}

Data received:

Child process PID: 1339310
In Child: Recieved:  {
  instrument: { type: 'Buffer', data: [ 203, 66, 165 ] },
  symbol: 'XRP-USDT',
  base_currency: { type: 'Buffer', data: [ 181, 205, 178 ] },
  base_symbol: 'XRP',
  quote_currency: { type: 'Buffer', data: [ 53, 15, 226 ] },
  quote_symbol: 'USDT',
  period: { type: 'Buffer', data: [ 202, 52, 73 ] },
  timeframe: '15m',
  timeframe_units: 15,
  bulk_collection_rate: 1440,
  interval_collection_rate: 4,
  sma_factor: 60,
  digits: 5,
  trade_state: { type: 'Buffer', data: [ 124, 122, 184 ] },
  state: 'Enabled',
  active_collection: 1,
  suspense: 0
}

The parent process is straight forward enough, collect and open a child for each enabled instrument; then, each process will attach to a websocket for updates.

The parent:

"use strict";

import { fork } from "child_process";
import { State } from "@db/interfaces/trade_state";

import * as InstrumentPeriod from "@db/interfaces/instrument_period";
import type { IInstrumentPeriod } from "@/db/interfaces/instrument_period";

//+--------------------------------------------------------------------------------------+
//| CProcess - Order Processing Class/Container                                          |
//+--------------------------------------------------------------------------------------+
export class CProcess {

  //+------------------------------------------------------------------------------------+
  //| Start - Loads order class array, syncs bar history, processes orders               |
  //+------------------------------------------------------------------------------------+
  async Start() {
    const start:Array<Partial<IInstrumentPeriod>> = await InstrumentPeriod.Fetch({ symbol: "XRP", state: State.Enabled });

    start.forEach((instrument) => {
      console.log('sent:', instrument)
      const child = fork("./class/child.ts");
      child.send({ type: "init", data: instrument });
    
      child.send({type: 'update'});
      console.log(`Child process PID: ${child.pid}`);

      child.on("message", (message) => {
        console.log(`Report from child process ${child.pid}:`, message);
      });
    
      child.on("exit", (code) => {
        console.log(`Child process ${child.pid} exited with code ${code}`);
      });
     })    
  }
}

The child

"use strict";

import { COrder } from "@class/order";
import { CFractal } from "@class/fractal";
import { State } from "@db/interfaces/trade_state";

import type { IInstrumentPeriod } from "@db/interfaces/instrument_period";
import type { IInstrument } from "@db/interfaces/instrument";
import type { ICandle } from "@db/interfaces/candle";

import * as InstrumentPeriod from "@db/interfaces/instrument_period";
import * as Instrument from "@db/interfaces/instrument";
import * as Candle from "@db/interfaces/candle";

//+--------------------------------------------------------------------------------------+
//| CChild - Order Processing Class/Container                                            |
//+--------------------------------------------------------------------------------------+
export class CChild {
  private Order: Array<COrder> = [];
  private Fractal: Array<CFractal> = [];
}

interface IRequest {
  type: string;
  data: IInstrumentPeriod;
}

interface IResult {
    symbol: string | string[]
    status: string;
    data: number;
    error: string;
}
const app = [];

//+------------------------------------------------------------------------------------+
//| Handle instrument start                                                            |
//+------------------------------------------------------------------------------------+
process.on("message", async (message:IRequest) => {
  const result:IResult = { symbol: "", status: "", data: 0, error: "" };

  if (message.type === "init") {

    const instrument:IInstrumentPeriod = message.data;
    console.log("In Child: Recieved: ",instrument);
    const [fractal] = await Instrument.Fetch({symbol: instrument.symbol});
    const props: Candle.IKeyProps = {
        instrument: fractal.instrument!,
        period: fractal.trade_period!,
        symbol: fractal.symbol!,
        timeframe: instrument.timeframe!,
      };
      console.log("fractal;",fractal, "props:",props)
    const candles: Array<Partial<ICandle>> = await Candle.Fetch(props, 10);
    const appclass = new CFractal(fractal,candles);
    app.push(appclass);

    result.symbol = instrument.symbol!;
    result.status = "ok";
  }

  if (message.type === 'update') {
    console.log("classes loaded: ", app.length)
  }
  if (typeof process.send !== "undefined") {
    process.send(result);
  }
});

Why all rows be afected when i tried to change once value of array created by fill method in JS? [duplicate]

I created a “pseudo 2D” array using Array() class and fill method, as:

let arr = [...Array(6).fill(Array(3).fill("$"))]

Then, i tried to change only one value with:

arr[3][1] = "hello" 

When I print “arr”, all second column be affected, but if I define a second array “arr2” element by element, it works.

Here the complete code:

let arr = [...Array(6).fill(Array(3).fill("$"))]

console.log(arr)

arr[3][1] = "hello"

console.log(arr)

let arr2 = [
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ]
]

arr2[3][1] = "world"
console.log(arr2)
// output
[
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ]
]

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'world', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]


// expected output

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'hello', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'world', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]

Thanks to anyone who can give me an idea why this occur.

npm ERR! ERESOLVE could not resolve (dependency conflicts)

I am using AWS (Amazon Web Services) specifically Amplify. I added the template that is provided by Amplify to GitHub and cloned it to my local machine and deployed it to Amplify that worked fine. I then modified the code locally and pushed the changes to GitHub which in turn attempted to deploy to Amplify, which then failed. I then read up online about this issue and have tried several methods to try and resolve the issue but nothing has worked so far. I have tried the following;

  1. Updating package-lock.json file 4 times
  2. npm audit fix --force
  3. deleting the package-lock.json file and npm install to create new one (I saved a copy of the original package-lock.json file)

After doing the above I am left with this output from the Amplify deployment.

Amplify output of why the deployment failed

This is my package.json file:

{
  "name": "amplify-vite-react-template",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@aws-amplify/ui-react": "^6.9.4",
    "aws-amplify": "^6.13.6",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@aws-amplify/backend": "^1.14.3",
    "@aws-amplify/backend-cli": "^1.5.0",
    "@types/react": "^19.0.12",
    "@types/react-dom": "^19.0.4",
    "@typescript-eslint/eslint-plugin": "^8.28.0",
    "@typescript-eslint/parser": "^8.28.0",
    "@vitejs/plugin-react": "^4.3.4",
    "aws-cdk": "^2.1005.0",
    "aws-cdk-lib": "^2.185.0",
    "constructs": "^10.4.2",
    "esbuild": "^0.25.1",
    "eslint": "^9.23.0",
    "eslint-plugin-react-hooks": "^5.2.0",
    "eslint-plugin-react-refresh": "^0.4.19",
    "tsx": "^4.19.3",
    "typescript": "^5.8.2",
    "vite": "^6.2.3"
  }
}

What do I need to do to rectify the errors?

Asynchronously looping a map (or array) in sequential order without await to avoid blocking UI updates [closed]

I have a map that must be looped through in sequential order, as i relies on i - 1 being finished. await is an obvious solution, however it is blocking the UI updates for the app aka the UI freezes. This loop takes several seconds to complete, and it’s critical that other code runs while this loop is running.

// Mocks
const functionThatReturnsMap = () => new Map([
  ['foo', 'FOO'],
  ['bar', 'BAR'],
  ['baz', 'BAZ'],
]);
const foo = async (i, m) => {
  console.log('Calling foo for iteration:', i);
  // do something async like an HTTP call
  await fetch(`https://echo.zuplo.io/${i}`);
  console.log(`foo[${i}] completed`);
};

async function bar() {
  let ref = functionThatReturnsMap();

  for (let i = 0; i < ref.size; i++) {
    await foo(i, ref);
  }
}

async function bat() {
  bar();
}

bat();
console.log('OMG, other code!');
.as-console-wrapper { max-height: 100% !important; }

For clarity, ref is a map that is being modified by foo by reference.

In a non-UI-updates-blocking way, how do I loop through my map ref asynchronously while ensuring that i - 1 is finished before i runs?

its possible combines “a fixed tooltip” (bindTooltip) when i using leaflet markers group?

When I am creating markers on the map, individually, I am using the “bindTooltip” tool to add fixed text below each marker.

Is it possible to do something similar, to have fixed text below each marker, but when the map is initialized with the markers grouped?

  iniciarMarkersGroup();
    dados.forEach(function (item, i) {

        let sInfo ='example';

        var marker;

        if (mapaAgrupado == "1") {
            marker = adicionarMarkerGroup(item.LAT, item.LONG, item.NAME, item.CUSTOM_IMG, sInfo);

        }
        else {
            marker = adicionarMarker(item.LAT, item.LONG, item.NAME, item.CUSTOM_IMG, sInfo);

            if (item.NAME != null && item.NAME != '') {
                marker.bindTooltip(item.NAME, {
                    permanent: true,
                    direction: 'bottom',
                    offset: [10, 10]
                });
            }
        }

if i use this example, when a user has “mapaAgrupado” , im trying exibes markers with a group function, and it is working. but if i try add a .bindTooltip , im receive a error, its possible use .bindTooltip with grouped markers?

Javascript tankgame, tanks wont move

I have followed a Youtube guide (https://www.youtube.com/watch?v=D9LqQEPGoo8) on how to make a 2D tank game with JS. I feel like I have done/written the same things as he did, but when I test out the movement of the tanks, my wont move at all?

Im completely new to programming, and trying to get a hang on it. I have tried to find a solution myself but I cant figure out the problem.

The images are getting draw, and I have have tested that it takes “key-inputs” and I can console.log its values, but it still doesn’t work.

Can you figure out whats wrong?

I have tried to switch a bit up on the variables, to see how the game would react and it feels like it does the right thing. I just doesn’t wont to move. Maybe the problem is at controls()?

<body>
    <canvas id="myCanvas" width="800" height="600"></canvas>
    <script type="text/javascript">
        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");
        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keyup", keyUpHandler, false);

        // Tanks udseende

        let tank1 = new Image();
        tank1.src = "tank1.png";
        let tank2 = new Image();
        tank2.src = "tank2.png";
        
        // Definering af variabler til controls

        let upPressed = false;
        let downPressed = false;
        let leftPressed = false;
        let rightPressed = false;
        let zeroPressed = false;
        let wPressed = false;
        let sPressed = false;
        let dPressed = false;
        let aPressed = false;
        let spacePressed = false;

        // keyUp og Down kontrollere om knappen bliver trykket eller ej
        // Tank 1 controls

    function keyDownHandler(e) {
            if (e.keyCode == 38)
        {
            upPressed = true;
        }
        if (e.keyCode == 40)
        {
            downPressed = true;
        }
        if (e.keyCode == 37)
        {
            leftPressed = true;
        }
        if (e.keyCode == 39)
        {
            rightPressed = true;
        }
        if (e.keyCode == 32)
        {
            spacePressed = true;
        }


        // Tank 2 controls
       
        if (e.keyCode == 87)
        {
            wPressed = true;
        }
        if (e.keyCode == 83)
        {
            sPressed = true;
        }
        if (e.keyCode == 65)
        {
            aPressed = true;
        }
        if (e.keyCode == 68)
        {
            dPressed = true;
        }
        if (e.keyCode == 96)
        {
            zeroPressed = true;
        }
    }
        
    function keyUpHandler(e) {

        if (e.keyCode == 38)
        {
            upPressed = false;
        }
        if (e.keyCode == 40)
        {
            downPressed = false;
        }
        if (e.keyCode == 37)
        {
            leftPressed = false;
        }
        if (e.keyCode == 39)
        {
            rightPressed = false;
        }
        if (e.keyCode == 32)
        {
            spacePressed = false;
        }


        // Tank 2 controls
       
        if (e.keyCode == 87)
        {
            wPressed = false;
        }
        if (e.keyCode == 83)
        {
            sPressed = false;
        }
        if (e.keyCode == 65)
        {
            aPressed = false;
        }
        if (e.keyCode == 68)
        {
            dPressed = false;
        }
        if (e.keyCode == 96)
        {
            zeroPressed = false;
        }
    }
   
        // For rotere img

    function drawImageRot(img, x, y, width, height, deg)
    {
        let rad = deg * Math.PI / 180;
        ctx.translate( x + width / 2, y + height / 2);
        ctx.rotate(rad);
        ctx.drawImage(img, width / 2 * -1, height / 2 * -1, width, height);
        ctx.rotate(rad * -1);
        ctx.translate(x + width / 2 * -1, y + height / 2 * -1);
    }

    let player1 = new Player(50, 100, 0, 40, 30);
    let player2 = new Player(300, 300, 0, 40, 30);


    function controls() 
    {
        // Tank1
        if (leftPressed)
        {
            player1.rot -= 1;
        }
        if (rightPressed) 
        {
            player1.rot += 1;
        }
        if (upPressed)
        {
            player1.x += Math.cos(player1.rot * Math.PI / 180);
            player1.y += Math.sin(player1.rot * Math.PI / 180);
        }
        if (downPressed)
        {
            player1.x -= Math.cos(player1.rot * Math.PI / 180);
            player1.y -= Math.sin(player1.rot * Math.PI / 180);
        }

        // Tank2
        if (aPressed)
        {
            player2.rot -= 1;
        }
        if (dPressed) 
        {
            player2.rot += 1;
        }
        if (wPressed)
        {
            player2.x += Math.cos(player2.rot * Math.PI / 180);
            player2.y += Math.sin(player2.rot * Math.PI / 180);
        }
        if (sPressed)
        {
            player2.x -= Math.cos(player2.rot * Math.PI / 180);
            player2.y -= Math.sin(player2.rot * Math.PI / 180);
        }
    }
    
    // Playerframework

    function Player(x, y, rot, w, h) 
    {
        this.x = x;
        this.y = y;
        this.rot = rot;
        this.w = w;
        this.h = h;
        this.canFire = true;
        this.score = 0;
        this.hasBeenHit = false;
    }

    function draw() 
    {
        ctx.clearRect (0, 0, myCanvas.width, myCanvas.height);
        controls();

        if (!player1.hasBeenHit)
    {
        drawImageRot(tank1, player1.x, player1.y, player1.w, player1.h, player1.rot);
    }
        if (!player2.hasBeenHit)
    {
        drawImageRot(tank2, player2.x, player2.y, player2.w, player2.h, player2.rot);
    }
    

    }

    setInterval (draw, 10);

    

    </script>
</body>

Why can ClientRequest.setTimeout take much longer than the provided duration?

In the following nodejs program, I am patching the dns.lookup function in order to investigate how a slow DNS lookup would behave when a timeout is set on a request. The DNS lookup will (appear to) take 10 seconds, so I expect my 1000ms timeout on the request to be triggered.

My timeout on the request is indeed triggered, but after around 5000ms instead of 1000ms as expected. Why could this be?

const dns = require('dns');
const http = require('http');
const lookup = dns.lookup;

const now = Date.now();

// I'm trying to simulate a slow DNS lookup here, to test how it behaves with the various nodejs
// timeout options.
dns.lookup = function patchedLookup(...args) {
  setTimeout(() => {
    lookup.apply(this, args);
  }, 10_000);
};

const req = http.request('http://joebarnett.xyz');

// The slow DNS lookup should cause this to timeout after 1000ms.
req.setTimeout(1000, () => {
  // Logs something like "timed out after 5007ms" - why not after 1000ms?
  console.error(`timed out after ${Date.now() - now}ms`);
  req.abort();
});

req.on('error', (err) => {
  console.error(`error after ${Date.now() - now}ms: ${err}`);
});

req.end();

Using Markdown-it HighlightJS incorrect rendering of block codes

I’m trying to learn about rendering Markdown inside HTML, and using Markdown-it and Highlight.js I use that code:

template.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="/js/styles/dark.min.css" />

        <title>Example Markdown-it</title>
    </head>
    <body>
        <div class="container">

        <div class="markdown">
        ## Example Markdown Content

        Example list:

        *   One

        *   Two

        *   Three

        A code segment:

        ```js
        window.onload = function() {
            var md = window.markdownit();
            var div = document.getElementsByClassName('markdown');
            for (var i = 0; i < div.length; i++) {
                var content = div[i].innerHTML;
                document.getElementsByClassName('markdown')[i].innerHTML = md.render(content);
            }
        }
        ```

        And now a C snippet:

        ```c
        #include <stdio.h>
        #include <other.h>

        int main() {
            printf("hello world!n");
            int x = 100;
            if (x > 50)
                printf("x is greater than 50n");
            return 0;
        }
        ```
        </div> <!-- end of markdown content -->

    </div>

    <script src="js/markdown-it.min.js"></script>
    <script src="js/highlight.min.js"></script>

    <script src="js/test.js"></script>
    </body>
</html>

and that is the Javascript:

  window.onload = function() {
    
    const md = markdownit({
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre><code class="hljs">' +
                   hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                   '</code></pre>';
          } catch (__) {}
        }

        return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    });

    var div = document.getElementsByClassName('markdown');
    for (var i = 0; i < div.length; i++) {
        var content = div[i].innerHTML;
        document.getElementsByClassName('markdown')[i].innerHTML =  md.render(content);
    }
}

the problem is when this render the Markdown produce this (incorrect) output:

![](how output render)

Is escaping < and > inside the code block although thats not I want, do that without Highlight.js, clearly is Markdown-it that produce the problem, and why auto-complete (incorrectly recognition) the #includes inside the block code?, I don’t know much Javascript
beyond the basic, but I don’t think the error is in this code, problably set any other option in Markdown-it to avoid this behavior?

The code used is from https://github.com/markdown-it/markdown-it?tab=readme-ov-file#syntax-highlighting:

const md = markdownit({
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre><code class="hljs">' +
                   hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                   '</code></pre>';
          } catch (__) {}
        }

        return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    });

And from How do I use markdown-it without node.js?:

    var div = document.getElementsByClassName('markdown');
    for (var i = 0; i < div.length; i++) {
        var content = div[i].innerHTML;
        document.getElementsByClassName('markdown')[i].innerHTML = md.render(content);
    }

Detect when a new Web Animation API is created

Is it possible to detect when a new Web Animation API is created? Something like an event-listener on the creation of Web Animation.

I guess that by pooling document.getAnimations() every few ms it should be possible, but I’d prefer a more resilient approach. When it is a CSS animations, I can use document.addEventListener("transitionstart", () => {…}) but I’m looking for something that works for all animations.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      #animatedElt {
          /* Any change will take 1s to complete */
          transition: all 5000ms;
      }
      moved {
          transform: translate(100px, 100px);
      }
    </style>
  </head>
  <body>
    <main id="screenshotTarget" style="background-color: red; width: 1000px; height: 800px;">
      This element will be paused in the middle of the transition. Can I then move it to a <b>precise</b> point it time, like move forward by 0.5s? 
      <div id="animatedElt" style="background-color: blue; width: 100px; height: 100px;" class="fadeMeMoveMeAnim">
      </div>
    </main>
    <script>
      document.addEventListener("transitionstart", () => {
        console.log("a transition starts. I want the same think but not specific to transitions");
      });
      setTimeout(() => {
        document.getElementById("animatedElt").style.transform = "translate(100px, 100px)";
        document.getElementById("animatedElt").style.backgroundColor = "green";
        setTimeout(() => {
          document.getAnimations().map(anim => {
            anim.pause();
          });
          setTimeout(() => {
            document.getAnimations().map(x => {
              x.currentTime += 500;
            })
          }
                   , 1000);
        }, 2000);
      }, 0)
    </script>
  </body>
</html>