CheckBox in React not firing

I have a component with a checkbox in it and for some reason it’s not firing. When I say firing I mean it does not console log or print out in the DOM. Nothing. I have tried onClick/onChange. Then I thought maybe this specific checkbox has a problem. But in the whole app no checkbox is firing. So maybe I am doing something wrong. Yes I have tried ChatGPT and checked elsewhere. Nothing works. Also restarted dev server.

import { useState } from "react";

export default function ThemeSwitcher() {
    const [checked, setChecked] = useState(false);

    const handleChange = () => {
        setChecked((prevCheck) => !prevCheck);
    };

    console.log(checked);

    return (
        <div>
            <label className="theme-switcher" htmlFor="themeswitch">
                <div className="background"></div>
                <input
                    type="checkbox"
                    id="themeswitch"
                    defaultChecked={checked}
                    onClick={() => handleChange()}
                />

                <div className="switch" >
                    <img alt="theme switch to dark" className="moon" src="/moon.png"></img>
                    <img alt="theme switch to light" className="sun" src="/sun.png"></img>
                </div>
            </label>
        </div>
    );
}

Why is my chess table not resetting before populating it?

I’m making a chess game and I start with an initial board. I have a position changing feature based on FEN. But when I want to update the board and reset before adding the new squares, it doesn’t reset.

const board = () => {
    let squares = [];

    const setBoard = fen => {
        squares = [];
        //populating squares logic
    };

    return { squares, setBoard };
};

This is where I invoke this function:

const startingFEN = "r1b1kb1r/ppp1pp1p/2nq1np1/3p4/3P1Q2/1P2P1P1/P1P2P1P/RNB1KBNR w KQkq - 0 1";

const chessBoard = board();
chessBoard.setBoard(startingFEN);
drawBoard(chessBoard.squares);

And this is where I update the board (dom.js)

fenButton.addEventListener("click", () => {
    chessBoard.setBoard(fenInput.textContent);
    drawBoard(chessBoard.squares);
});

the squares = [] line in the setBoard function breaks the code, but without that line, it just adds an other board without resetting the previous one.

Recursive tree function traversal

I have a tree that represents an excel function, where node contains name : function_name (for example SUM);type : function_type (function or number); arguments : function_ arguments. The whole problem for me is that arguments can be another function. I already have an algorithm that works on simple functions, but with a lot of nesting, arguments are lost. I would like to know how to solve this. I will attach my code below.

function getSubFormulas(node) {
  if (node.type === "function") {
    var args = node.arguments.map(arg => {
   console.log(arg)
      if (arg.arguments) {
        // Если аргумент - это массив, извлекаем свойство name из каждого элемента
        console.log(arg.arguments.map(subArg => getSubFormulas(subArg).name).join(","))
        return arg.name +"(" +arg.arguments.map(subArg => getSubFormulas(subArg).name).join(",") + ")";
      } else {
        // Если аргумент не является массивом, извлекаем свойство name
        return getSubFormulas(arg).name;
      }
    }).join(",");
    console.log(args + " args ")
    
    var name = `${node.name}(${args})`;
  //  console.log(name);
    const formula = {
      name: name,
      depth: node.depth
    };
    return [formula, ...node.arguments.filter((elem) => elem.type == "function").map(getSubFormulas).flat()];
  } else {
    if (node.operand == null) {
      let temp_name = node.value;
      return {name: temp_name}
    }
    let temp_name = 0 - node.operand.value;
    return {name : temp_name}
  }
}

I’ve already tried using map to call for all arguments, but still something falls in.

How to get data from loader hook into an array then pass in to component

please see my code below. I am currently trying to create a gantt chart using syncfusion react gantt charts. The code works fine as is but I now want to change the data in the GanttData array which is the data source for the GanttComponent so that it is dynamic. I am using react router dom to pull in data from a database using the loader hook. Once I get this data I want to pull out some dates and put them in the GanttData array but I don’t know how as I can’t use useLoaderData unless it is in a function. Can anyone assist? Apologies if this isn’t clear. Please let me know if you need more information.

export const loader = async ({ request, params }) => {
  try {
    const { data } = await customFetch.get(`/projects`);
    return data;
  } catch (error) {
    toast.error(error?.response?.data?.msg);
    return redirect("/dashboard/all-jobs");
  }
};

const GanttData = [
  {
    TaskID: 1,
    ProjectNo: "29895",
    TaskName: "Stoneybridge WTW",
    StartDate: new Date("04/02/2019"),
    EndDate: new Date("05/21/2019"),
    subtasks: [
      {
        TaskID: 1.1,
        TaskName: "Sodium Carbonate",
        StartDate: new Date("04/02/2019"),
        Duration: 4,
        Progress: 150,
        comments: "unlucky",
        subtasks: [
          {
            TaskID: 1.11,
            TaskName: "Design",
            StartDate: new Date("04/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.12,
            TaskName: "Workshop",
            StartDate: new Date("05/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.13,
            TaskName: "Site",
            StartDate: new Date("06/02/2019"),
            Duration: 30,
            Progress: 150,
          },
        ],
      },
      {
        TaskID: 1.2,
        TaskName: "PACl",
        StartDate: new Date("04/02/2019"),
        Duration: 4,
        Progress: 150,
        comments: "unlucky",
        subtasks: [
          {
            TaskID: 1.21,
            TaskName: "Design",
            StartDate: new Date("04/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.22,
            TaskName: "Workshop",
            StartDate: new Date("05/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.23,
            TaskName: "Site",
            StartDate: new Date("06/02/2019"),
            Duration: 30,
            Progress: 150,
          },
        ],
      },
      {
        TaskID: 1.3,
        TaskName: "Ammonium Sulphate",
        StartDate: new Date("04/02/2019"),
        Duration: 4,
        Progress: 150,
        comments: "unlucky",
        subtasks: [
          {
            TaskID: 1.31,
            TaskName: "Design",
            StartDate: new Date("04/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.2,
            TaskName: "Workshop",
            StartDate: new Date("05/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 1.13,
            TaskName: "Site",
            StartDate: new Date("06/02/2019"),
            Duration: 30,
            Progress: 150,
          },
        ],
      },
    ],
  },
  {
    TaskID: 2,
    ProjectNo: "31139",
    TaskName: "Barra WTW",
    StartDate: new Date("04/02/2019"),
    EndDate: new Date("05/21/2019"),
    subtasks: [
      {
        TaskID: 2.1,
        TaskName: "Sodium Carbonate",
        StartDate: new Date("04/02/2019"),
        Duration: 4,
        Progress: 150,
        comments: "unlucky",
        subtasks: [
          {
            TaskID: 2.11,
            TaskName: "Design",
            StartDate: new Date("04/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 2.12,
            TaskName: "Workshop",
            StartDate: new Date("05/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 2.13,
            TaskName: "Site",
            StartDate: new Date("06/02/2019"),
            Duration: 30,
            Progress: 150,
          },
        ],
      },
      {
        TaskID: 2.2,
        TaskName: "Ammonium Sulphate",
        StartDate: new Date("04/02/2019"),
        Duration: 4,
        Progress: 150,
        comments: "unlucky",
        subtasks: [
          {
            TaskID: 2.21,
            TaskName: "Design",
            StartDate: new Date("04/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 2.22,
            TaskName: "Workshop",
            StartDate: new Date("05/02/2019"),
            Duration: 30,
            Progress: 150,
          },
          {
            TaskID: 2.23,
            TaskName: "Site",
            StartDate: new Date("06/02/2019"),
            Duration: 30,
            Progress: 150,
          },
        ],
      },
    ],
  },
];

const splitterSettings = {
  position: "30%",
};

const timelineSettings = {
  timelineUnitSize: 60,
  timelineViewMode: "Month",
  topTier: {
    unit: "Year",
  },
  bottomTier: {
    unit: "Month",
  },
};

function GanttChart() {
  const { projects } = useLoaderData();

  console.log(projects);
  console.log(projects[0].projectEnd);
  const taskFields = {
    id: "TaskID",
    name: "TaskName",
    startDate: "StartDate",
    duration: "Duration",
    progress: "Progress",
    child: "subtasks",
  };
  return (
    <GanttComponent
      dataSource={GanttData}
      taskFields={taskFields}
      height="530px"
      width="1200px"
      splitterSettings={splitterSettings}
      allowResizing={false}
      timelineSettings={timelineSettings}
      collapseAllParentTasks={true}
    >
      <ColumnsDirective maxWidth="100" minWidth="70" width="10">
        <ColumnDirective
          field="TaskID"
          width="100"
          maxWidth="100"
          minWidth="100"
        ></ColumnDirective>
        <ColumnDirective
          field="ProjectNo"
          headerText="Project Number"
          width="80"
          allowResizing={false}
          maxWidth="100"
          minWidth="100"
        ></ColumnDirective>
        <ColumnDirective
          field="TaskName"
          headerText="Task Name"
          width="200"
          maxWidth="100"
          minWidth="100"
        ></ColumnDirective>
      </ColumnsDirective>
      <Inject services={[Resize]} />
    </GanttComponent>
  );
}

export default GanttChart;

java script map function does not affect the array

trying to modify the array values by adding a new field to the array objects

userTree.Decorations = await Promise.all(userTree.Decorations.map(async (decoration) => {

        const decorationType = await Decorationtype.findOne({ decorationTypeName: decoration.decoratrionTypeName });

        decoration.imgURL = decorationType.imgURL;
        console.log(decoration.imgURL);
    
        return decoration;
    }));

the modification does not take place after running this function and replacing the original array with the new array

How to load an image directly from url into buffer in node.js

I would like to load an image from Internet directly to stream without saving it to disk an load it again.

Something like
fs.createReadStream(imageDirectory)
but just for URLs.

I want to give this image direct to an AI API and don’t want to save the image all 300ms to the harddisk.

I read many articles, but never worked

Need help fixing import error for SparkLine Components using React.js

Receiving 4 errors when trying to run my project, seems to be not recognizing the SparkLineComponent even though I’ve installed the dependencies and have the correct import statements. I’ve provided screenshots of my code/errors.

(https://i.stack.imgur.com/w2IUA.jpg) (These are the errors I’m receiving when I try to run my project)

import React from 'react';
import { SparklineComponent, Inject, SparklineTooltip } from '@syncfusion/ej2-react-charts';

const SparkLine = ({ id,height,width,color,data,type,currentColor }) => {
    return (
        <SparklineComponent
        id={id}
        height={height}
        width={width}
        lineWidth={1}
        valueType="Numeric"
        fill={color}
        border={{ color: currentColor, width: 2 }}
        dataSource={data}
        xName="x"
        yName="y" 
        >
            <Inject services={[SparklineTooltip]} />
        </SparklineComponent>
    )
}

export default SparkLine

I’m creating a e-commerce admin dashboard app, and trying to implement charts to view income earnings, and economic progression.

Variable input error in Postfix Expression Calculator

This postfix calculator works with an implemented stack, it works fine for normal postfix expressions such as ‘2 5 +’, but there seems to be an issue in variable handling. When i run it, it returns this error:
Output:

7
27

   index.js:44
                throw new Error(`Invalid token encountered: ${token}`);
                ^

    Error: Invalid token encountered: A
        at PostfixCalculator.evaluate (index.js:44:19)
        at Object.<anonymous> (/runtime/javascript/3zxrd96tq_3zxykq39r/index.js:78:24)
        at Module._compile (node:internal/modules/cjs/loader:1103:14)
        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
        at Module.load (node:internal/modules/cjs/loader:981:32)
        at Function.Module._load (node:internal/modules/cjs/loader:822:12)
        at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
        at node:internal/main/run_main_module:17:47

I have posted the code below, please let me know what i have done wrong and how i can improve and fix it, i am a beginner so any advice will be appreciated thanks.

class PostfixCalculator {
  constructor() {
    // Initialize an empty stack to hold operands and an empty symbol table for variables
    this.stack = [];
    this.symbolTable = {};
  }

  // Method to evaluate postfix expressions
  evaluate(expression) {
    // Split the expression into tokens (operands, operators, or variables) using spaces
    const tokens = expression.split(' ');

    // Iterate through each token in the expression
    for (let token of tokens) {
      if (!isNaN(token)) {
        // If the token is a number, push it onto the stack as an operand
        this.stack.push(parseFloat(token)); // Push operands to the stack
      } else if (token in this.symbolTable) {
        // If the token is a known variable, push its corresponding value onto the stack
        this.stack.push(this.symbolTable[token]); // Push variable values to the stack
      } else {
        // If the token is an operator (+, -, *, /) or '=', perform the corresponding operation
        switch (token) {
          case '+':
            this.performOperation((a, b) => a + b); // Addition operation
            break;
          case '-':
            this.performOperation((a, b) => a - b); // Subtraction operation
            break;
          case '*':
            this.performOperation((a, b) => a * b); // Multiplication operation
            break;
          case '/':
            this.performOperation((a, b) => a / b); // Division operation
            break;
          case '=':
            // Perform variable assignment by popping value and variable name from the stack
            const value = this.stack.pop();
            const variable = this.stack.pop();
            this.symbolTable[variable] = value; // Store variable value in the symbol table
            break;
          default:
            // Throw an error for an invalid token encountered
            throw new Error(`Invalid token encountered: ${token}`);
        }
      }
    }

    // Check if the stack contains only one element after evaluation
    if (this.stack.length !== 1) {
      throw new Error('Invalid expression');
    }

    // Return the final result by popping the last element from the stack
    return this.stack.pop(); // Result will be the only element in the stack
  }

  // Method to perform arithmetic operations on operands
  performOperation(operation) {
    // Pop the last two operands from the stack
    const operand2 = this.stack.pop();
    const operand1 = this.stack.pop();
    // Perform the specified operation on the operands
    const result = operation(operand1, operand2);
    // Push the result back onto the stack
    this.stack.push(result);
  }
}

// Example usage:
const calculator = new PostfixCalculator();

// Evaluate postfix expressions
console.log(calculator.evaluate('3 4 +')); // Output: 7
console.log(calculator.evaluate('3 4 5 + *')); // Output: 27

// Handle variable assignments
console.log(calculator.evaluate('A 2 =')); // Setting variable A to 2
console.log(calculator.evaluate('B 3 =')); // Setting variable B to 3
console.log(calculator.evaluate('A B *')); // Output: 6 (Multiplication of variables A and B)

Accessing the fields of nested objects in JS causes TypeError

I get TypeError: undefined is not an object when I try to access the value of a nested object using object[x][y]

I have tried to add quotes to the keys (i.e player/monster), but it still does not work. So I am not really sure what the error is. How can I access the value ([‘x’, “bar”]) using variables?

const frames =  {
  player: {
    "UP": ['x', "bar"],
    "DOWN": ['x', "foo"]
    //etc
  },
  monster: {
    "UP": ['y', "fizz"],
    "DOWN": ['y', "buzz"]
    //etc
  }
}

//works fine
console.log(frames.player["UP"]);
let x = "DOWN";
console.log(frames.monster[x]);

//TypeError
let type = "player";
x = "DOWN";
console.log(frames[type][x]);

Are timing requirements in webRtc between calling setRemoteDescription and addIceCandidate?

I have implemented webrtc in 2 browsers that physically work on one local machine (one browser I will call as “local”, another – “remote”). The browser – Firefox 112.0.1, TURN, STUN servers are not used.

All strings (offer, answer, ice candidates) are transferred from one to another browser manually (slow transfer – via copy and paste).
“Remote” gets an offer from the “local” and processes it by rtc2_RegisterRemoteOffer (see code below).
This function creates answer of the “remote”.
Then:
(1) the negotiationneeded event fired on the “remote”,
(2) because of (1) “remote” creates offer and generates it’s own ice candidates (up to here neither “local” nor “remote” ice candidates I didn’t transfer to each other).
(3) Then after few seconds on the “remote” iceconnectionstate fired with the status failed.

The questions are:

  1. What may be a reason of iceconnectionstate gets failed – see (3) ?
  2. Could this happen because I didn’t have enough time to send any ice candidate from the “local” to the “remote” after sending offer ?
  3. Is the case (2) – is correct behavior ? Should the “remote” create your own answer when it processes the answer of the “local” ?
  4. If it shouldn’t (question 3), then how the “remote” should correctly process it’s own negotiationneeded event ?

The code of the “rtc2_RegisterRemoteOffer”

   function rtc2_RegisterRemoteOffer(remoteOfferText) {
        // Register an offer of a remote machine..
        // Input:
        //      - remoteOfferText - string - offer text.

        let stateStr = webRtc.peerConnection.signalingState;

        let logMsg = "rtc2_RegisterRemoteOffer is called. State = " + stateStr;
        DisplayLogMessage(logMsg);
        console.log(logMsg);

        console.log("==remoteOfferText==" + remoteOfferText);
        console.log(remoteOfferText);
        remoteOfferObj = {type: "offer", sdp: remoteOfferText};
        let remoteDescr = null;
        try {
            remoteDescr = new RTCSessionDescription(remoteOfferObj);
        }
        catch (e) {
            remoteDescr = null;
            DisplayErrMessage("Can't create SDP. Errmsg = " + e.message);
        }

        if (remoteDescr === null) {
            // error - do nothing
            DisplayErrMessage("remoteDescr === null !!!");
        }
        else {
            // set remote description
            let remotedescrPromise = webRtc.peerConnection.setRemoteDescription(remoteDescr)
            .then(function Resolve_rdp() {
                let msg = "rtc2_RegisterRemoteOffer.setRemoteDescription -- fulfilled";
                DisplayLogMessage(msg);
                console.log("===> ", msg);
            },

            function Reject_rdp(e) {
                let msg ="rt2c_RegisterRemoteOffer.setRemoteDescription REJECTED. Msg = " + e.message;
                DisplayErrMessage(msg);
                console.log("===> ", msg);

            }
            );  // let remotedescrPromise =

            stateStr = webRtc.peerConnection.signalingState;
            DisplayLogMessage("rtc2_RegisterRemoteOffer - Creating answer for the remote. State = " + stateStr);

            // create an answer to the remote offer

            let answerTextPromise = webRtc.peerConnection.createAnswer().then(
                // resolve
                function resolve_createAnswer(answer) {
                    // answer is generated

                    stateStr = webRtc.peerConnection.signalingState;
                    let msg = "rtc2_RegisterRemoteOffer.createAnswer - resolved. State = " + stateStr;
                    DisplayLogMessage(msg);
                    console.log(msg);
                    // (***) HERE I get:
                    // rtc2_RegisterRemoteOffer.createAnswer - resolved. State = have-remote-offer
                    // set the answer as the local description
                    webRtc.peerConnection.setLocalDescription(answer,

                        function resolve_setLocalDescription_answer() {
                            // resolve -- local description is set
                            console.log("===> ", "rtc2_RegisterRemoteOffer.SetLocalDescription fulfilled.");
                            // ----------------------------------------------------
                            // (***) HERE I get: the message above
                        },
                        function reject_setLocalDescription_answer() {
                            // resolve -- local description is set
                            console.log("ERROR = (setLocalDescription in rtc_RegisterRemoteOffer) is REJECTED");
                        }
                    );
                    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

                    // Display local answer for the remote
                    PutLocalAnswerText(answer.sdp);
                    DisplayStatus("Send answer to a remote");

                    // --- try to add local audio/video tracks to the remote ---
                    let tracksAdded = rtc2_addTracks();
                    if (tracksAdded) {
                        // our tracks sent to the remote
                        let msg = "rtc2_RegisterRemoteOffer_Our tracks sent on remote answer.";
                        DisplayLogMessage(msg);
                        console.log(msg);
                    }
                    else {

                        // can't access <mediaDevices>
                        let msg = "ERR1 - rtc_RegisterRemoteOffer_Our tracks WERE NOT sent on remote answer.";
                        DisplayErrMessage(msg);
                        console.log(msg);
                    }

                },
                function reject_createAnswer(e) {
                    let msg = "rt2c_RegisterRemoteOffer.createAnswer - REJECTED. Msg = " + e.message +
                                " State = " + stateStr;
                    DisplayErrMessage(msg);
                    console.log(msg);

                }

            );
        } // if (remoteDescr === null) else

    }   // function rtc2_RegisterRemoteOffer

The offer of the “local”

v=0
o=mozilla...THIS_IS_SDPARTA-99.0 672388715268626096 0 IN IP4 0.0.0.0
s=-
t=0 0
a=sendrecv
a=fingerprint:sha-256 65:F6:31:2A:FF:DD:7C:E1:89:83:C6:F1:8C:61:25:8F:E4:AD:0A:B6:8A:A7:D0:A3:0E:E0:DF:C8:99:5F:85:73
a=group:BUNDLE 0
a=ice-options:trickle
a=msid-semantic:WMS *
m=application 9 UDP/DTLS/SCTP webrtc-datachannel
c=IN IP4 0.0.0.0
a=sendrecv
a=ice-pwd:e0e9063fdcde2bd9f4c3068accca0907
a=ice-ufrag:4386e8e0
a=mid:0
a=setup:actpass
a=sctp-port:5000
a=max-message-size:1073741823

Javascript AssertionError: expected false to equal true

using JS to solve the following task:

In order to purchase an item online we need to check that the user’s password is correct and that they have enough money to afford it. Use what you’ve learned about logic and comparison operators to complete the code.

Steps are:

  1. Assign an expression to isPasswordCorrect that checks that secret is the correct password, ‘hunter2’.
  2. Assign an expression to isAffordable that checks their funds are at least 10.99.
  3. Assign an expression to isPurchasable that checks that both isPasswordCorrect and isAffordable are true.
function canWeBuyIt(secret, funds) {
  const isPasswordCorrect = secret === "secret" // true

  const isAffordable = funds >= 10.99 // true

  const isPurchasable = isPasswordCorrect && isAffordable // true

  return {
    isPasswordCorrect,
    isAffordable,
    isPurchasable
  };
}

However, I am getting the following errors:

Should return true if the password is correct and wallet amount is larger than 10.99

✕ AssertionError: expected false to equal true

Should work for a wallet amount of exactly 10.99

✕ AssertionError: expected false to equal true

js TouchEvent: when pinching with two fingers and lifting one of them up, how to kown which finger had lifted?

i’am working in a complicated touching gesture, and meet this problem:

let cachedStartTouches: TouchList;
let cachedMoveTouches: TouchList;

function onStart(ev: TouchEvent) {
  // length equals 2 when two fingers pinch start
  cachedStartTouches = ev.touches;
}

function onMove(ev: TouchEvent) {
  // length equals 2 when two fingers pinching moving
  cachedMoveTouches = ev.touches; 
}

function onEnd(ev: TouchEvent) {
  // equals 1 when one finger holds up early, but another one still moving
  ev.touches.length

  // the cachedTouches's length is still two now,  
  // how to known which idx had been canceled, 0 or 1 ?
  const idx = getCanceledTouchesIdx(????)

  // remove it from cache
  cachedStartTouches.splice(idx, 1)
  cachedMoveTouches.splice(idx, 1)
}

more genral case: N fingers pinching, and lifting some of them?

Form is returning null without any reason

thanks to give me your time.

I actually coding a login page but i can’t write form.addEventListener()
When i console.log(form) it return null and i don’t know why
For the js side :

const form = document.getElementById("form");
console.log(form)

form.addEventListener('submit', (event) => {
    event.preventDefault
    console.log(event)
    console.log(form)
})

For the html side :

[...]
        <form id="form">
            <label for="email"> Entrez votre Email : </label>
            <input id="email" type="email" name="email" placeholder="Email ..." required>
            <label for="mdp"> Entrez votre Mot de Passe : </label>
            <input type="password" name="password" id="mdp" placeholder="Mot De Passe ..." required>
            <input type="submit" name="envoyer" id="send" value="Se connecter">
        </form>
[...]

thanks you if you read that !

I tried to change form, re try in another folder but nothing change

How to save a file inside React Native project and access and edit it?

I can’t access this .docx file that is inside the docs folder of the project’s assets folder.
I have already looked for ways to access this .docx file, but I have not been successful in accessing or making this file/folder stay within the project build.

I want this .docx file to be inside the project so that I can access, create a copy of the file and edit that copy after pressing a button.

I already have the variables with name, contract number, address, email and phone ready to add in their specific positions in this .docx file.
In each position of the .docx file where these variables will be placed, it is written as name and phonenumber so that I can find these specific words and swap them for the variables after clicking a button.
After that, this file will be saved in the cell phone’s documents folder.

Is there a way to have this file/folder compiled with the project and be able to access it to make this edit?

Precedence of setImmediate() and setTimeout() callbacks in CommonJS vs ESM

Calling setTimeout with setImmediate has unpredicted behaviour if using CommonJS modules. But if you switch to ESM (“type”: “module” in package.json), it will always execute setImmediate before setTimeout.

setTimeout(() => {
  console.log('timeout');
}, 0);

setImmediate(() => {
  console.log('immediate');
});

Why does this happen? Is it related to the fact that in ESM modules are loaded asynchronously?