Node.js + TypeScript – Files Executing Out of Order [duplicate]

I’m working on a Node.js + Express project using TypeScript with the "module": "nodenext" option in tsconfig.json. The issue is that my files execute out of order
Project Setup

tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "outDir": "dist",
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "baseUrl": "./",
    "typeRoots": ["./node_modules/@types", "./src/@types"],
    "types": ["node", "express"],
    "paths": {
      "#src/*": ["src/*"]
    }
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

package.json

{
...
"main": "server.ts",
  "type": "module",
  "scripts": {
    "lint": "eslint src --ext .ts",
    "lint:fix": "eslint src --ext .ts --fix",
    "dev": "nodemon --watch . --ext ts --exec tsx server.ts",
    "build": "tsc",
    "start": "node server.js"
  },
  "license": "ISC",
  "dependencies": {....},
  "devDependencies": {....},
  "imports": {
    "#src/*": "./src/*"
  }
}

./server.ts (Entry Point)

console.log('server.ts is executing');

import dotenv from 'dotenv';
dotenv.config({ path: './config.env' });

console.log('ENV:', process.env.NODE_ENV);

import mongoose, { MongooseError } from 'mongoose';
import { server } from '#src/app.js';
......

./src/controllers/socketController.ts

console.log('socketMessageController.ts is executing');

import appConfig from '#src/config/appConfig.js';
import userSockets from '#src/helper/socketMap.js';
.....

Issue
When I run the project using: npm run dev

The output is:

enter image description here

This means socketMessageController.ts is executing before server.ts, causing process.env to be undefined in that file. Right now, I am hardcoding environment variables as a workaround.

Expected Behavior:
server.ts should execute first, loading environment variables before any other files that depend on them.
Other modules should get process.env properly populated.

CORS problem while sending request to netlify dev server

I’m working on a chrome devtools panels extension. In it I have:

const toDbBtn = document.getElementById("toDbBtn");

toDbBtn.addEventListener("click", async () => {
  const dbName = document.getElementById("textBox").value;

  // const result = await chrome.storage.local.get(["yourKey"]);

  const storedJSON = await chrome.storage.local.get(["yourKey"]);
  console.log("Result from storage:", storedJSON);

  if (storedJSON.yourKey) {

    const parsedArray = JSON.parse(storedJSON.yourKey);
    console.log("Parsed Array:", parsedArray);
    const partArray = parsedArray.slice(0, 30);
    console.log("partArray", partArray);
    const data = {
      dbName: dbName,
      savedArray: partArray,
    };

    const postable = JSON.stringify(data);
    console.log("postable", postable);
    // http://localhost:8888/.netlify/functions//updateCollection.js

    const response = await fetch(
      "http://localhost:8888/.netlify/functions/updateCollection",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          // "Access-Control-Allow-Origin": "*",
          // "Access-Control-Allow-Methods": "POST",
          // "Access-Control-Allow-Headers": "Content-Type",
        },
        body: postable,
      }
    );

    const result = await response.json();
    console.log("Response from server:", result);
  } else {
    console.log("Value not found in storage for key: yourKey");
  }
});

I’m planning to send some data to a netlify function, and so decided to test locally using “NTL DEV” command.

my target ntl function is:

exports.handler = async function (event, context) {
  const obj = JSON.parse(event.body);
  console.log("obj: ", obj);   
  const collectionName = obj.dbName;
  const objArray = obj.savedArray;
  console.log("objArray: ", objArray);
  console.log("collectionName: ", collectionName);

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: data,
    }),
  };
};

When I push the devtools button, I get:

Request from ::ffff:127.0.0.1: OPTIONS /.netlify/functions/updateCollection

based on CORS error while sending request from Browser to play server even after sending CORS header , I assume that the browser starts of by sending a OPTIONS request. But I’m not sure based on https://cli.netlify.com/commands/dev/ how to set a cors header like “Access-Control-Allow-Origin”: “*” . How can I get this working?

Backtracking confusion

Concerning Javascript, I’ve been trying to understand backtracking lately and it’s really confusing. Specifically, I’ve been trying to understand the permutation problem, which when given an array, we want all of the possible permutations of that array:

function permute(nums) {
    let result = [];
    function backtrack(temp = []) {
        if (temp.length === nums.length) {
            result.push([...temp]);  
            return;
    }
        for (let i = 0; i < nums.length; i++) {
            if (temp.includes(nums[i])) continue;  
            temp.push(nums[i]);       
            backtrack(temp);          
            temp.pop();               
    }
  }
  backtrack();
  return result;
}

Let’s consider nums = [1,2] for simplicity.

From what I understand, we start at temp=[], at i=0 temp -> [1], and backtrack is supposed to search for the other possible values (just 2). It ignores the deletion of the supposed value in temp.pop() and goes back to the loop where i=1 now and temp [1] -> [1,2] and now that it satisfies the condition of length, a copy of this temp array is appended to the result array. So my question is, what happens after this appending?

Supposedly, the code provided above does return [[1,2],[2,1]], which is correct but I don’t understand why. After the appending, apparently we pop the final value from temp, now it’s at [1] and we restart the loop in i, since we finished it to obtain [1,2]. We go through i=0 again, but temp already has the value 1 so we continue. Then it gets added 2 again, and the backtrack sends this result to check the initial condition of length, isn’t it? Apparently, it must pop twice and start the loop at i=1 for the backtrack to have backtrack([2]) and then search for the missing 1.

I don’t understand where my flaw is but I know there is some misinterpretation somewhere, I just don’t understand where.

How to activate the middle mouse button on a page with likes in instagram?

The page https://www.instagram.com/your_activity/interactions/likes/ contains my likes. There are no tags or any mention of shortcode in the HTML. The link to the post looks like this: https://www.instagram.com/p/DH61Qm7t-cR , where DH61Qm7t-cR is the shortcode. DH61Qm7t-cR is not mentioned anywhere on the page. Each block is a div, clicking on which will open the post.

However, if you execute this code
JSON.parse = ((parse) => function() {
  const parsed = parse.apply(this, arguments);
  if (arguments[0]?.includes('DH61Qm7t-cR')))
    console.log('JSON.parse', parsed);
  return parsed;
})(JSON.parse);

and left click on the post, then I will get a JSON array with our shortcode at this address: payload.payload.payload.result.route_match_infos[0].instanceParams.shortcode

That is, the shortcode appears after clicking on the post with the left mouse button. Could you please tell me how I can activate the middle key so that when I click on it, the current page is not refreshed and the post I am interested in is opened in a new tab (i.e. I want to get the default action when the middle mouse button is pressed)?

All candidate resources failed to load. Media load paused

I wrote a script to display mp4 clips FTP’d to the web server from a Reolink CCTV recorder. There could be hundreds sometimes over thousand of these clips along with their jpeg pictures displayed by date and time.

By default I use preload="none" not to overwhelm the browser on page load. I click some of those videos to determine if I should keep or delete. However, after about 20-40 video loads I get this error in FireFox console All candidate resources failed to load. Media load paused.

After this error the browser will not play anymore videos until it is refreshed/reloaded. Sometimes ajax delete function will also stop working. When I refresh the page all of the selections to delete will go away rendering my time reviewing the videos useless.

<video width="320" height="240" controls preload="none">
   <source src="/path/to/video.mp4" type="video/mp4" onerror="playerError()">
</video>

After adding onerror="playerError()" extended the number of videos I can play before the browser stops working. This function gets triggered few times before the browser stops working.

function playerError() {
    console.log('playerError function triggered'); 
} 

Is there any jquery/javascript code that can be added to this function to make the browser continue to work? Basically is there a way to reset Media load paused situation?

In my opinion FireFox works best with html5 video tags, better than chrome and safari. I can try other browser if it may work better.

Blazor WebAssembly SyntaxError: Unexpected token ‘{‘

We are using Blazor WebAssembly .NET 9. Our app has stopped working on iOS 15.8 and we found this issue that seems to be the same issue but for Blazor Server. I tried to start editing the javascript as described in that post but got stuck quickly on mismatches server and wasm. Has anyone solved to run a .NET 9 Blazor WebAssembly on iOS 15.8 and could give guidance on this? I am not sure what we can do to get our app running on iOS 15.8 again. The console error is the same as that post

Unexpected token '{'

p5js move in camera direction

Blockquote

I am trying to make a first person player controller. I can make the camera pan/tilt on mouse movement, but I am having problems trying to make the player move in the direction the camera is facing. Right now it just moves in the normal axes and the movement is not associated with the camera movement. I tried using the camPan variable to move it but so far I haven’t had any luck.
Code:

let cam;
let x = 0;
let y = -50;
let z = 0;
let camPan = 0; // Camera rotation around Y axis
let camTilt = 0; // Camera rotation around X axis
let speed = 1;
let sensitivity = 4;
let moveDir = 0; // Direction of movement


function setup() {
    createCanvas(windowWidth, windowHeight, WEBGL);
    background(100);
    cam = createCamera();
    debugMode();
}

function draw() {
    background(100);
    controller();
    cam.setPosition(x, y, z);
    cam.pan(camPan);
    cam.tilt(camTilt);
}

function mousePressed() {
    requestPointerLock(); // Lock cursor on click
}

function controller() {
    if (keyIsDown(87)) { // Forward
        z -= speed;
    }
    if (keyIsDown(83)) { // Backward
        z += speed;
    } 
    if (keyIsDown(65)) { // Left
        x -= speed;
    }
    if (keyIsDown(68)) { // Right
        x += speed;
    }
}

function mouseMoved() {
    camPan = -movedX / width / 2 * sensitivity;
    camTilt = movedY / height / 2 * sensitivity;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>

I also noticed that the camera would drift occasionally. I don’t know if that was a problem with the trackpad that I was using or something, but if you know why, it would be useful.

Buttons On Click Functioning with same ID different and different attributes

I have an HTML webpage with a sample of buttons as shown part of a Django Application that fills in the name and town after inserting the values:

{% for person in page_obj %}
       <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button>
{% endfor %}
<button id="NotifyBtn" name="Billy" town="Bob">Press Me</button>
<button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button>
<button id="NotifyBtn" name="Milly" town="House">Press Me</button>

Then I have a JS that does the following:

document.getElementById("NotifyBtn").addEventListener("click", function(){
            var name = this.getAttribute("name");
            var town = this.getAttribute("town");
            fetch("{% url 'alert_via_JSON_Response' %}", {
                method: "POST",
                headers: {
                    "X-CSRFToken": "{{ csrf_token }}",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}`
                 })
                }).then(response => response.json())
                    .then(data => alert(data.status));
        });

In my Django application I have the following:

def alert_via_JSON_Response(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        message = data.get('message', "Error in sending email")
        return JsonResponse({"status": f"{message}"})
    return JsonResponse({"status": f"No Message"})

Right now, when I click on the webpage, only one button works and sends a JSON response to the webpage, it doesn’t work if I press another button after pressing the first button. Is there a way to press each button when needed and display the JSON response for each button?

Download Link Needs to Show Timer Before Redirecting Not Working

I’ve got a slight issue with my download link, it displays the link out but the timer is not showing the link just disappears instead of showing the timer after the link has been clicked example “start download” then a time will appear from 10 seconds then they will get redirected to the download page.

var i = 0;

function myFunction(url) {
  var tt = setInterval(function() {
    i = i + 1;
    var counter = 6 - i;
    button.innerHTML = 'Download will start in:' + counter;
    if (counter === 0) {
      clearInterval(tt);
      window.location = url //redirect here
    }
  }, 1000);
};
<button id="button">
  <a href="#" class="card-price" id="button1"       onclick="myFunction('download1.zip')">Click To Download</a>
 </button>

How to mock History API using Sinon, Mocha and JSDOM?

I’ve writing a simple single-page application from scratch, and it has a simple router class. It works fine, and now is time to create unit tests for router. For testing, I use Mocha + Chai + JSDOM.

Router have back() and forward() functions, which are just calling window.history.back() and window.history.forward(). Unit test for that functions looks pretty simple:

import { expect } from "chai";
import { Router } from "./router.ts";

describe('Router test', () => {
    let router;
    let elementConstructor;
    let window = globalThis.window;

   function createRouter() {
       return new Router();
   }

   beforeEach(()=>{
       router = createRouter();
   })

   it('Router can go forward', () => {
       window.history.pushState({page: 'messages'}, '', 'messages.html');
       window.history.pushState({page: 'index'}, '', 'index.html');
       window.history.pushState({page: 'login'}, '', 'login.html');
       router.back();
       router.back();
       router.forward();
       expect(window.history.state['page']).to.eq('index');
   });
})

But… JSDOM doesn’t support history API, so this calls just doing nothiing and test always falling. It seems that Sinon library can mock History API, but I failed to find some useful documentation for this case. Does anybody know, where I can to read about mocking history API via Sinon?

Web technology information technology [closed]

Using your HTML, CSS, and JavaScript skills, create a web application to display the 2025 election results for the specified political parties. The application should feature a pie chart with clearly labeled, color-coded sections representing DAD (45%), PPP (5%), CCCC (27%), and MCD (23%). Ensure each segment is distinguishable with unique colors.

The series points show below the x axis when multiple y axis are added

I have requirement to have multiple y axis and series but only one y axis is visible at the time. But when i change the visibility of other y axis to false, then the series data shows below the x axis. If I set setClipping(false), data gets cut off but i do need to display that above x axis.

I could create the issue in the example – https://lightningchart.com/js-charts/interactive-examples/edit/lcjs-example-0007-sharedAxis.html?isList=false

Just add axisY2.setVisible(false); below line 85.
Can you please help me find the right solution to the problem ?

How to get javascript called by javascript to work

Go easy on me – I don’t spend a lot of time in javascript. Plus I’m having a hard time explaining my situation to be able to look for solutions that may already exist.

I work for a healthcare organization that uses a service called Healthwise to provide medical library content for our website. Healthwise provides their content via an API that outputs full HTML code, including CSS and Javascript. I have successfully connected to the API and can display content from it on a test server.

To get that content displayed within my production website, I have to feed it in via Javascript. This is where I’m running into problems. My Javascript pulls in the HTML and CSS just fine. But any Javascript from the API is not working, whether it’s a linked file or inline code.

I considered grabbing the Javascripts from the API and calling them directly from my Javascript. But the files and inline code all change depending on the content the API is serving. So short of downloading and calling EVERY script they have every time, which I know would be horrible practice, there’s no way for me to do that. How can I get my Javascript to accept and run the Javascript provided by the API?

DOM with Pseudo Element using JS

I’m currently working on a JavaScript application and I have a div that uses two pseudo-elements (::before and ::after). I’ve set background images on both pseudo elements using CSS.

I want to change the background images of those pseudo elements dynamically when a certain event happens in JavaScript.

As far as I know we can’t directly select or manipulate pseudo-elements like ::before or ::after using JavaScript, so instead I’m targeting the main element itself. How can I change the background images of the pseudo-elements using JavaScript?

If anyone knows a good way to do this, I’d really appreciate the help.