How to properly type express route handlers?

New to express, and I’m trying to understand the ‘proper’ way to have type-safe route handlers. How can I fix this? Clearly my code ‘runs’, but I’m not sure how to properly type handlers in express. Say I have a route ‘events’ and some methods:

app.use("/events", eventsRoutes);

within my eventsRoutes I define a simple get, but it has errors in my IDE:

//... 

router.get("/user/:userId", (req, res) => { // <- This is the error
  const { userId } = req.params;
  const collection = EVENTS_COLLECTION.get(userId);
  if (!collection) {
    return res.status(200).json([]);
  }

  // iterate the keys and return an array of events
  const eventsArray: Event[] = [];
  for (const [date, events] of collection.entries()) {
    events.forEach((event) => {
      event.date = new Date(date);
      eventsArray.push(event);
    });
  }

  res.status(200).json(eventsArray);
});

// ...

No overload matches this call. The last overload gave the following error.

Argument of type '(req: Request<{ userId: string; }, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>, number>) => Response<...> | undefined' is not assignable to parameter of type 'Application<Record<string, any>>'.
  Type '(req: Request<{ userId: string; }, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>, number>) => Response<...> | undefined' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more.

How can I fix this? Clearly my code ‘runs’, but I’m not sure how to extend or properly ‘type’ the Request object in express.

Simultaneous scenes transitions with ThreeJs

I’m developing using ThreeJs and I’m trying to implement transition between scenes, I primarely used the TransitionRenderPass as in this example, this render pass constructor takes two scenes and two cameras and allow you to animate the transition from one scene to the other.

It works great if your usecase is to start transition one after the other, but in my case I’d like to start a second transition while the first one is still occurring ? Let’s say that I’m first transitionning from scene A to scene B, this first transition reached its middle point, then I decide to transition from scene B to scene C.

I was kind of able to reach the result by duplicating the shader used behind TransitionRenderPass and modifying it to take the output of the previous pass (tDiffuse) and the renderTarget of the destination scene (instead of scene A and scene B) that way I was able to chain my customer Shader Pass, and if the first was meant to transition from RenderPass (being scene A) to scene B at progress 0.66, and the second was meant to transition from tDiffuse (being the transition from scene A to B) to scene C at progress 0.33, I got what I was looking for (the render was scene A, B and C showing at different level of transition)

That said, I encountered other issue, weird bohr effect when I started to add mesh to my scene for instance. Anyway I was wondering if you didn’t know a better way, maybe I’m missing something regarding the TransitionRenderPass

Does Microsoft Edge have a bug?

I had an <input> tag attached to a <datalist> tag. This showed a popup of all the items when typing in the <input> control. It was working great.

But I’ve updated my code to dynamically populate the <datalist> using JavaScript, and now it doesn’t work in Microsoft Edge. The popup only shows previously entered items. It does not show anything from the <datalist>. I tried it on Chrome, and it works just fine.

I’ve searched around online and don’t find that this is a well-known issue. Does anyone know if this is a bug?

Javascript display raw JSON instead of rendering the HTML content like the “index” button

I’m developing a Django web application that allows users to follow each other and view a feed of posts from the users they follow. I have a button that triggers an AJAX request to a Django view designed to fetch and render the relevant posts. My Django view correctly retrieves the posts from users the currently logged-in user follows and returns them as a JSON response. However, when my JavaScript code receives this response, it doesn’t render the posts into the page as HTML. Instead, the browser displays the raw JSON data. I expect the JavaScript to use the JSON data to update the page with rendered HTML content representing the posts, but this isn’t happening. How can I ensure that my JavaScript correctly processes the JSON and renders the posts as HTML?
thanks for helping ❤️

post.js:

document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
const index = document.querySelector('#index')
const following = document.querySelector('#following')

if(index) {
    index.addEventListener('click', () => load_data('index'));
}

if (following) {
    following.addEventListener('click', () => load_data("following"));
}

// By default, load the index
load_data('index');
});

function load_data(type) {
console.log("type:", type);
let url;
if (type == "index") {
    url = "/post"
} else if (type == "following") {
    url = "/following"
} else {
    return
}
console.log("url: ", url)
fetch(url)
    .then(response => response.json())
    .then(posts => {
        console.log("posts:", posts);
        const postsContainer = document.querySelector("#postsContainer");
        if(postsContainer) {
            postsContainer.innerHTML = '';
        }
        posts.forEach(post => {
.....
}

layout.html:

          <li class="nav-item">
        <a id="index" class="nav-link" href="{% url 'index' %}">All Posts</a>
      </li>
      {% if user.is_authenticated %}
      <li class="nav-item">
        <a class="nav-link" href="{% url 'create-post' %}">New Post</a>
      </li>
      <li class="nav-item">
        <a id="following" class="nav-link" href="{% url 'following' %}">Following</a>
      </li>

views.py:

@login_required
def following(request):
    user = request.user
    user_followings = Follow.objects.filter(follower=user)
    posts = []
    for user_following in  user_followings:
        posts.extend(Post.objects.filter(user=user_following.followed).order_by('-date'))

    return JsonResponse([post.serialize() for post in posts], safe=False)

Problem updating parent max-height in nested accordions (measurement is wrong)

I’m trying to build a nested accordion structure where each accordion, when clicked, updates both its own and its parent’s maxHeight dynamically. However, whenever I open a child accordion, the parent’s height is sometimes computed incorrectly. I expect it to be around 288px, for example, but it ends up at 160px, or part of the content is cut off.

Below is a simplified version of my click handler. When a .aside-accordion button is clicked, I set the child accordion’s maxHeight, then use a while loop to update any parent .accordion-content elements:

document.addEventListener('click', function(event) {
  if (event.target.matches('.aside-accordion')) {
    const button = event.target;
    const accordionMenu = button.nextElementSibling;
    const buttonArrow = button.querySelector('.arrow');

    button.classList.toggle('active');

    if (button.classList.contains('active')) {
      buttonArrow.classList.add('rotate-180');
      accordionMenu.style.maxHeight = accordionMenu.scrollHeight + 'px';
    } else {
      buttonArrow.classList.remove('rotate-180');
      accordionMenu.style.maxHeight = 0;
    }

    let parentContent = accordionMenu.parentElement.closest('.accordion-content');
    while (parentContent) {
      const parentButton = parentContent.previousElementSibling;
      if (parentButton && parentButton.classList.contains('active')) {
        // Here I'm assigning the parent's actual height
        parentContent.style.maxHeight = parentContent.scrollHeight + 'px';
      }
      parentContent = parentContent.parentElement.closest('.accordion-content');
    }
  }
});

Live demo

Expectation: When the child accordion opens, all parent accordions should automatically expand to accommodate the child’s height, so the content is fully visible.

Issue: Sometimes the parent’s maxHeight ends up smaller than expected or partially hides the content, requiring a second click to fix it. I’m using transition: max-height 0.3s ease; overflow: hidden; on all accordions.

I’ve tried using a large hard-coded value (e.g., 999999px) instead of scrollHeight and it “fixes” the issue, but that’s obviously not a clean solution. requestAnimationFrame or small setTimeout calls sometimes help, but still produce inconsistent results. I also tested transitionend, but sometimes the content “jumps” on the initial open.

Question: How can I reliably update the parent maxHeight in a nested accordion so that the first click always shows the correct expanded height (without glitches or having to click again)?

Can we recreate Adobe Animate or Macromedia Flash in Javascript?

I loved creating animations with Adobe Animate. But all subscriptions and money made me quit the application and try and find an alternative (Opentoonz and etc..).

I’ve been very curious to know the source code of Macromedia Flash and see how it was developed, but obviously, I didn’t find anything.

How complex would it be to recreate something similar to Adobe Animate but in a browser ? What should I take in consideration If I’d work to develop such software ? With all its complex features like Timeline, Frames, Symbols, Graphics, Export, Library, Drawing tools and even throw in some Cloud features and collaboration..

Can it be performant in complex scenes (while having backgrounds, FX like blur and etc..) ?

I thought of using PixiJS, it provides speed and efficient rendering when using a lot of assets.
I researched more similar applications in the browser, but haven’t found what I’m looking for…

Electron JS: spawn() works fine with “python –version” but with “python” I don’t get any output

I’m using Electron JS and trying to execute a command in a child process using spawn() from the child_process module.

When I run the command python --version, it correctly outputs the version of Python in the child process. However, when I run just python, the process seems to start but doesn’t output anything, and the behavior appears inconsistent.

Here is a simplified version of my code:

const { spawn } = require('child_process');



const child = spawn('python', [], { shell: true });



child.stdout.on('data', (data) => {

  console.log(`stdout: ${data}`);

});



child.stderr.on('data', (data) => {

  console.error(`stderr: ${data}`);

});



child.on('close', (code) => {

  console.log(`Child process exited with code ${code}`);

});


What I expect:

Running python should launch the interactive Python REPL and provide output.

What actually happens:

When I run python --version, it works fine.

When I run just python, there is no output or REPL interaction visible in my app.

Additional Details:

Electron version: v34.0.0

Node.js version: v23.6.0

IDE: Visual Studio Code

OS: Windows 11 24H2

What could be causing this issue? Do I need to set up the child process differently to handle REPL or interactive commands in Electron?

Cypress type() method doesn’t enter the full desired string

I’m trying to fix a cypress test. The problem is that from time to time type() method doesn’t enter the full string.
The test has a good pass rate but still shows some fails. For example

pageClass.getElMethod().type(“test”);

And as a result I can see from 1 to 3 last characters.

I tried different options:

  • use click() method before type();
  • use focus();
  • use focus() + realType();
  • use should(“be.visible”) for the element;

But all of these attempts were failed.

Trying to find any other options.

YOLO object detection model in React Native CLI project

I trained an object detection model using python yolo. i tested the .pt model, good result also the .onnx same acccurate results. but when i use the same .onnx model in react native cli it has random results and wrong.
The model is in main/assets, and it’s imported correctly, but the output is always different than the python testing results.

import * as ort from 'onnxruntime-react-native';
import {Platform} from 'react-native';
import * as RNFS from 'react-native-fs';
import ImageResizer from 'react-native-image-resizer';
import {toByteArray} from 'base64-js';

const IMAGE_SIZE = 640;
const CHANNELS = 3;

export type DetectionResult = {
  className: string;
  confidence: number;
  bbox: {
    x: number;
    y: number;
    width: number;
    height: number;
  };
};

class ImageDetectionService {
  private static instance: ImageDetectionService;
  private session: ort.InferenceSession | null = null;
  private classes: string[];
  private isInitialized: boolean;
  private modelPath: string | null;

  private constructor() {
    this.session = null;
    this.classes = [
      'classe1',
      'classe2',
      'classe3',
      'classe4',
    ];
    this.modelPath = null;
    this.isInitialized = false;
  }

  static getInstance(): ImageDetectionService {
    if (!ImageDetectionService.instance) {
      ImageDetectionService.instance = new ImageDetectionService();
    }
    return ImageDetectionService.instance;
  }

  private async loadModelFromAssets(): Promise<string> {
    if (Platform.OS === 'android') {
      const tempDirPath = `${RNFS.CachesDirectoryPath}/models`;
      const tempModelPath = `${tempDirPath}/best.onnx`;

      try {
        await RNFS.mkdir(tempDirPath);
        const tempModelExists = await RNFS.exists(tempModelPath);
        if (!tempModelExists) {
          await RNFS.copyFileAssets('best.onnx', tempModelPath);
        }
        return `file://${tempModelPath}`;
      } catch (error) {
        console.error('Error copying model file:', error);
        throw error;
      }
    } else {
      return 'best.onnx';
    }
  }
  // Add to initialize method after creating session
  async initialize(): Promise<void> {
    try {
      this.modelPath = await this.loadModelFromAssets();
      console.log('Loading model from path:', this.modelPath);
      this.session = await ort.InferenceSession.create(this.modelPath);

      // Debug model information
      if (this.session) {
        const inputNames = await this.session.inputNames;
        const outputNames = await this.session.outputNames;
        console.log('Model input names:', inputNames);
        console.log('Model output names:', outputNames);
      }

      this.isInitialized = true;
      console.log('ONNX model loaded successfully');
    } catch (error) {
      console.error('Error initializing ONNX model:', error);
      throw error;
    }
  }

  private async preprocessImage(imageUri: string): Promise<Float32Array> {
    try {
      const resizedImage = await ImageResizer.createResizedImage(
        imageUri,
        IMAGE_SIZE,
        IMAGE_SIZE,
        'JPEG',
        100,
        0,
        undefined,
        false,
        {onlyScaleDown: true},
      );

      const base64Data = await RNFS.readFile(resizedImage.uri, 'base64');
      const rawImageData = toByteArray(base64Data);
      const float32Data = new Float32Array(IMAGE_SIZE * IMAGE_SIZE * CHANNELS);

      const MEAN = [0.485, 0.456, 0.406];
      const STD = [0.229, 0.224, 0.225];

      for (let i = 0; i < rawImageData.length; i += 3) {
        const r = rawImageData[i] / 255.0;
        const g = rawImageData[i + 1] / 255.0;
        const b = rawImageData[i + 2] / 255.0;

        float32Data[i] = (r - MEAN[0]) / STD[0];
        float32Data[i + 1] = (g - MEAN[1]) / STD[1];
        float32Data[i + 2] = (b - MEAN[2]) / STD[2];
      }

      const nchwData = new Float32Array(1 * CHANNELS * IMAGE_SIZE * IMAGE_SIZE);
      for (let c = 0; c < CHANNELS; c++) {
        for (let h = 0; h < IMAGE_SIZE; h++) {
          for (let w = 0; w < IMAGE_SIZE; w++) {
            const srcIdx = h * IMAGE_SIZE * CHANNELS + w * CHANNELS + c;
            const dstIdx = c * IMAGE_SIZE * IMAGE_SIZE + h * IMAGE_SIZE + w;
            nchwData[dstIdx] = float32Data[srcIdx];
          }
        }
      }

      return nchwData;
    } catch (error) {
      console.error('Error preprocessing image:', error);
      throw error;
    }
  }

  async detectObjects(imagePath: string): Promise<DetectionResult[]> {
    if (!this.isInitialized || !this.session) {
      throw new Error('Model not initialized. Call initialize() first.');
    }

    try {
      const inputTensor = await this.preprocessImage(imagePath);
      const feeds = {
        images: new ort.Tensor('float32', inputTensor, [
          1,
          3,
          IMAGE_SIZE,
          IMAGE_SIZE,
        ]),
      };

      const results = await this.session.run(feeds);
      return this.processResults(results);
    } catch (error) {
      console.error('Error running detection:', error);
      throw error;
    }
  }
  private calculateIoU(box1: any, box2: any): number {
    const x1 = Math.max(box1.x, box2.x);
    const y1 = Math.max(box1.y, box2.y);
    const x2 = Math.min(box1.x + box1.width, box2.x + box2.width);
    const y2 = Math.min(box1.y + box1.height, box2.y + box2.height);

    if (x2 < x1 || y2 < y1) return 0;

    const intersection = (x2 - x1) * (y2 - y1);
    const area1 = box1.width * box1.height;
    const area2 = box2.width * box2.height;
    const union = area1 + area2 - intersection;

    return intersection / union;
  }

  private nonMaxSuppression(
    detections: DetectionResult[],
    iouThreshold: number = 0.5,
  ): DetectionResult[] {
    // Sort by confidence
    const sorted = [...detections].sort((a, b) => b.confidence - a.confidence);
    const selected: DetectionResult[] = [];

    for (const detection of sorted) {
      let shouldSelect = true;

      for (const selectedDetection of selected) {
        const iou = this.calculateIoU(detection.bbox, selectedDetection.bbox);
        if (iou > iouThreshold) {
          shouldSelect = false;
          break;
        }
      }

      if (shouldSelect) {
        selected.push(detection);
      }
    }

    return selected;
  }

  private processResults(
    results: Record<string, ort.Tensor>,
  ): DetectionResult[] {
    const outputTensor = results['output0'];
    if (!outputTensor) {
      console.error('Output tensor is undefined');
      return [];
    }

    const data = outputTensor.data as Float32Array;
    const rawDetections: DetectionResult[] = [];
    const numClasses = this.classes.length;

    // The output shape is (1, 8, 8400)
    // 8 represents: [x, y, w, h, confidence, class1_score, class2_score, class3_score, class4_score]
    const CONFIDENCE_THRESHOLD = 0.3;
    const NUM_BOXES = 8400;
    const BOX_DATA = 8;

    for (let box = 0; box < NUM_BOXES; box++) {
      const baseOffset = box * BOX_DATA;

      // Get box coordinates
      const x = data[baseOffset + 0];
      const y = data[baseOffset + 1];
      const width = data[baseOffset + 2];
      const height = data[baseOffset + 3];

      // Get confidence score
      const confidence = data[baseOffset + 4];

      if (confidence > CONFIDENCE_THRESHOLD) {
        // Find class with highest probability
        let maxClassProb = 0;
        let classId = 0;
        for (let c = 0; c < numClasses; c++) {
          const classProb = data[baseOffset + 5 + c];
          if (classProb > maxClassProb) {
            maxClassProb = classProb;
            classId = c;
          }
        }

        const detection: DetectionResult = {
          bbox: {
            x: x,
            y: y,
            width: width,
            height: height,
          },
          className: this.classes[classId],
          confidence: confidence,
        };

        rawDetections.push(detection);
      }
    }
    console.log(this.nonMaxSuppression(rawDetections));
    // Apply NMS to filter overlapping boxes
    return this.nonMaxSuppression(rawDetections);
  }
}

export default ImageDetectionService;

Nextjs app running fine in dev mode but giving error on build

My nextjs app is working fine in dev mode but when I am trying to build it for production it gives an error about array.filter that filter is not defined.

const { questions, answers } = useQuiz();
    const correctAnswersCount = answers.filter((answer, index) => answer === questions[index].correct).length; <!--Error Here -->

    return (
        <div className="flex flex-col items-center justify-center bg-gray-100">
            <div className="w-[70vw] mx-auto">
                <h1 className="text-xl font-bold text-center">Quiz Results</h1>
                <DonutChart correctAnswers={correctAnswersCount} totalQuestions={questions.length} />
                </div><div className='flex justify-center mt-40'>
                <Link href="/review">
                    <button className="mt-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
                        Review Answers
                    </button>
                </Link>
            </div>
        </div>

How to click an element using a node ID from the accessibility tree in Puppeteer?

I’m working with Puppeteer to automate interactions on a webpage. I have retrieved information from the accessibility tree using Puppeteer’s page.accessibility.snapshot() method. The snapshot provides elements with unique id values, but these IDs do not correspond to regular HTML attributes. I want to programmatically click on an element using its node ID from this snapshot.

Here’s what I’ve tried so far:

I used page.accessibility.snapshot() to retrieve the accessibility tree and find the node ID.
Attempted to use page.evaluate() with the retrieved id, but it’s unclear how to map this back to the actual DOM element.
Explored using ARIA roles (role: "button") and names (name: "Recherche Google"), but this doesn’t guarantee matching the specific node.

I expected to interact with the element using the node ID or any accessible path, but I haven’t found a reliable way to map the accessibility node ID to a clickable element in Puppeteer.

Get Steam Market Converted Price

I am currently trying to get some Steam Market listings in my program, but am running into the following problem:

When I send the request with this sample program:

import axios from "axios";

const url = "https://steamcommunity.com/market/listings/730/AK-47%20%7C%20Asiimov%20%28Field-Tested%29";

import axios from "axios";

axios.get(url, { headers })
  .then(response => {
    console.log("Response:", response.data);
  })
  .catch(error => {
    console.error("Error:", error);
  });
  

I get an HTML page from which I can extract the data in a Variable. However, when I use javascript, only general information is displayed, but not the converted price, which is important for me, because otherwise the items are in any currency.

In the code I am also logged in with a Module called “SteamUser” and this is the same account with which I receive the converted price as a variable via the browser.

Do you Guys know, what i need to change, to also get the converted Price?

Important: An account with a wallet is required, only then will steam automatically convert the currency. I actually have that, the request is sent with a logged in account that already has a wallet and as already mentioned it works in the browser without any problems

React Testing Library: Unable to Find Element by data-testid During Test

I am encountering an error when testing a React component using React Testing Library. The test fails to find an element with data-testid=”resCard” even though I believe it should be rendered.

Error details

● Should render the body component with search

TestingLibraryElementError: Unable to find an element by: [data-testid="resCard"]                                                
                                                                                                                                 
Ignored nodes: comments, script, style                                                                                           
<body>                                                                                                                           
  <div>
    <div
      class="body"
    >
      <div
        class="filter flex items-center"
      >
        <input
          class="border border-solid border-black px-3 py-1 ml-5"
          data-testid="searchInput"
          type="text"
          value="burger"
        />
        <button
          class="search-container  px-4 py-2 bg-green-100 ml-3 rounded-lg"
        >
          Search
        </button>
        <div
          class="search m-3 p-3 items-center"
        >
          <button
            class="px-5 py-4 bg-grey-500 rounded-lg"
          >
            Top Rated Restuarant
          </button>
        </div>
      </div>
      <div
        class="flex flex-wrap"
      />
    </div>
  </div>
</body>

  34 | fireEvent.click(searchBtn);
  35 |
> 36 | const cardsAfterSearch = screen.getAllByTestId("resCard");
     |                                 ^
  37 |
  38 | expect(cardsAfterSearch.length).toBe(1);
  39 | });

  at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
  at node_modules/@testing-library/dom/dist/query-helpers.js:76:38
  at node_modules/@testing-library/dom/dist/query-helpers.js:109:15
  at Object.getAllByTestId (src/components/__test__/Search.test.js:36:33)

Search.test.js

import Body from "../Body";
import { fireEvent, render , screen} from "@testing-library/react";
import MOCK_DATA from "../mock/bodyMock.json";
import { act } from '@testing-library/react';
import { BrowserRouter } from "react-router-dom";
import "@testing-library/jest-dom";
//Global is a global object wherever the body component is rendered, creating mock fetch function.

global.fetch = jest.fn(() =>{
    return Promise.resolve({
        json: () => {
            return Promise.resolve(MOCK_DATA);
            //Here the data that return.
        }
    })
});

test("Should render the body component with search", async() => {

//Act is basically a promise
    await act(async () => 
        render(<BrowserRouter><Body />
        </BrowserRouter>
        )
    );


const searchBtn = screen.getByRole("button", { name: "Search" });

const searchInput = screen.getByTestId("searchInput");

fireEvent.change(searchInput, { target: { value: "burger" } });

fireEvent.click(searchBtn);

const cardsAfterSearch = screen.getAllByTestId("resCard");

expect(cardsAfterSearch.length).toBe(1);
});

RestaurantCard.js

  import { CDN_URL } from "../utils/constants";

const styleCard = {
    backgroundColor: "#f0f0f0"
 };

const RestuarantCard =(props) =>{
    const {resData} = props;
    console.log(resData);
    const {cloudinaryImageId,name,cuisines,avgRating,costForTwo} = resData?.info;
    
    return(
       <div data-testid = "resCard" className="m-4 p-4 w-[300px] rounded-lg" style={styleCard}>
          <img className = "rounded-lg w-full h-[180px] object-cover" src ={CDN_URL + cloudinaryImageId}/>
          <h3 className="font-bold text-lg truncate">{name}</h3> 
          <h4 className="whitespace-normal overflow-hidden text-ellipsis">{cuisines.join(",")}</h4>
          <h4> {avgRating}</h4>
          <h4> {costForTwo}</h4>
       </div>
    );
 };

 export const withPromotedLabel = (RestuarantCard) => {
   return (props) => {
      return (
         <div>
            <label>Promoted</label>
            <RestuarantCard {...props}/>
         </div>
      )
   }
 }
 export default RestuarantCard;

Inside RestaurantCard.js I have provide data-testid = “resCard”, but still the issue persists.

1.How can I resolve this error,please help.

Grid Arrangement Algorithm for Fitting HTML elements on the Screen

I recently built a web extension that can scrape HTML elements from a page and open a new tab with those elements. I came across a problem that I’ve been working on for hours but I’m not coming up with a good solution. Basically I want to fit these elements on the screen by arranging them somehow, while also being able to scale them. I plan to implement this algorithm in Javascript so I can use it with my web extension.

Goals:

  • Scale rectangles as uniformly as possible (ex. not scaling one down by 0.5 and another up by 5)
  • Utilize as much space as possible

Constraints:

  • Maintain aspect ratio of each rectangle
  • No rotating rectangles
  • No overlapping rectangles

Here’s an example of what my extension outputted in a new tab (was trying to make a cheat sheet):

https://imgur.com/yNzIp2w

I’ve done a decent amount of searching into bin packing algorithms (although that’s pretty new for me) and similar topics but haven’t found any that include the ability to scale the rectangles.

Any help here would be much appreciated!

What is the source of this error attempting to read my local html file using Node.js?

This is all happening on my one machine — both the server and the client machine are the same. I am learning on w3schools and have successfully completed the Node.js examples in order until this one where I am attempting to read an html file to use as content to display. The server starts correctly as seen in the console with the blinking cursor like the prior examples, however upon trying to access localhost through chrome, I get the console logged error as well as a notification in chrome with “127.0.0.1 refused to connect.”

error:

node:_http_outgoing:949
    throw new ERR_INVALID_ARG_TYPE(
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at write_ (node:_http_outgoing:949:11)
    at ServerResponse.write (node:_http_outgoing:904:15)
    at ReadFileContext.callback (C:path-to-file-omitteddemo_readfile.js:7:9)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:299:13) {
  code: 'ERR_INVALID_ARG_TYPE'
}

Node.js v22.13.0

The two files verbatim as I used them from w3schools.

demofile1.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

demo_readfile.js

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Using Powershell to start node.js instance with my file using ‘node C:path-to-filefilename.js’, I tried running powershell as an admin. I tried doing some searches on google and stack overflow to identify this error elsewhere, and while they appeared similar, the ones I found did not apply directly to my issue as far as I know, nor did they at least give me a resolution.