how to construct an array on server that is passed to client as part of a script.JS file

I’m trying to build a small single page web application. the application has the basic index.html script.JS and style.CSS files. The body element (in index.html) sets up a button and an empty section element. the script populates the section element with the first of two lists. currently the script includes the lists in array objects like the following:

let list_1 = [ 'a', 'b', 'c']
let list_2 = [ 'd', 'e', 'f']

canBtn.innerText = "CAN'T"
tagLine.innerText = 'I can still ...'
list_1.forEach(el => {
    const div = document.createElement('div')
    div.innerText = el
    document.querySelector('.text-container').appendChild(div)

initially, the client renders the first list. After that, when the user clicks the button, the script switches to show the second list. the button can be used to toggle between the lists.

what I want to do is build each list by reading a corresponding file. Something like:

const fileContent = fs.readFileSync(filePath, 'utf-8');
const lines = fileContent.split('n');

this should create the array I’m looking for, but how do I include this in the script.JS file sent to the client?

Or is there a better way to accomplish what I’m trying to do? I only started learning JavaScript last month and node.JS a week ago so I am pretty new to this.

I’ve tried using node and EJS templates. I was expecting, well at least hoping, to have the server read the files each time the pages is requested

Five Digit Time Conversion to Standard AM, PM time

I am using an IP camera to fetch the date and time of a particular Video. The date is in the correct format but time is actually a five digit number like this “33092”. What time format it is? and how I can convert it into standard AM PM time format in javascript?

I thought this is second elapsed since midnight but by converting it I am not getting the desired AM PM time.

RESULT OF API TIME

ASP.NET MVC script rendering issue

I have old asp.net projects with pages and script as below

_Layout

<script src='@(Url.AbsoluteContent("~/js/some-js.js"))'></script>
<script src='@(Url.AbsoluteContent("~/js/another-js.js"))'></script>
@RenderSection("Scripts", required: false)

Child Page

@section Scripts {
   <script src='@Html.Raw(Url.AbsoluteContent("~/js/child-js.js"))'></script>
}

However, when rendering happens

<script src="https://example.com/js/some-js">&lt;/script>
<script src="https://example.com/js/another-js">&lt;/script>
<script src="https://example.com/js/child-js">&lt;/script></script>

script ending tag is encoded and js is not available for its usage.
any possible resolution?

I have tried and not working.

<script src='@Html.Raw(Url.AbsoluteContent("~/js/some-js.js"))'></script>

I’ve tested this API on Postman and it works when i try use the same API on Flowise to retrieve information using a custom tool

This is the code snippet for my custom tool :

const url = 'http://13.61.32.121:8069/api/ReadRegister';
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Cookie': 'frontend_lang=en_US; session_id=580aa695bcce5778f63c0c6a231567216afc1cec'
},
body: JSON.stringify({
conversation_id: "27679856633",
params: {
fields: [
"task_id",
"x_employee_id",
"x_daily_attendance_date",
"x_daily_attendance_status",
"x_daily_start_time",
"x_daily_end_time",
"stage"
]
}
})
};

try {
const response = await fetch(url, options);
const text = await response.text();
return text;
} catch (error) {
console.error(error);
return '';
}

Used the API on Flowise to retrieve created register records but didn’t get any records. When testing the API on Postman I get the records. your text

Tom Select – Preventing Selection of Child Options When Parent is Selected

I’m using Tom Select with a multi-select dropdown for a folder structure where options are grouped by parent folders. For example, if I select a top-level folder like app, I want any child options like app/Helpers or app/Http to automatically be disabled, preventing them from being selected.

Here’s the current setup:

  • Using Tom Select with the checkbox_options plugin.
  • The select field includes optgroup elements, and options have data-groups attributes to indicate their parent grouping.

HTML Structure:

<select id="myFolders" name="folders[]" multiple autocomplete="off">
    <optgroup label="app">
        <option value="app" selected>app</option>
        <option value="app/Helpers">app/Helpers</option>
        <option value="app/Http">app/Http</option>
    </optgroup>
</select>

Javascript I tried.

const tomSelect = new TomSelect('#myFolders', {
    plugins: {
        'checkbox_options': {
            'checkedClassNames':   ['ts-checked'],
            'uncheckedClassNames': ['ts-unchecked'],
            'className': 'form-check-input'
        },
        'remove_button': {
            title:'Remove this item',
        }
    },
    onChange: function () {
        updateDisabledOptions(this);
    }
});

function updateDisabledOptions(tomSelectInstance) {
    const selectedValues = tomSelectInstance.getValue();
    const selectedGroups = new Set(selectedValues);

    Object.values(tomSelectInstance.options).forEach(option => {
        const optionElement = document.querySelector(`.ts-dropdown [data-value="${option.value}"]`);
        
        if (optionElement) {
            const checkbox = optionElement.querySelector('.form-check-input');

            if (checkbox) {
                const isChildOfSelectedGroup = Array.from(selectedGroups).some(
                    group => option.value.startsWith(group + '/')
                );

                if (isChildOfSelectedGroup) {
                    optionElement.classList.add('disabled');
                    checkbox.setAttribute('disabled', true);
                } else {
                    optionElement.classList.remove('disabled');
                    checkbox.removeAttribute('disabled');
                }
            }
        }
    });
}

Problem: The function is adding the disabled attribute to child checkboxes, but it doesn’t prevent them from being selected. Even with aria-disabled and disabled attributes set, the checkboxes are still selectable.

Expected Outcome: If a parent folder like app is selected, any child folders (e.g., app/Helpers) should be automatically disabled and not selectable.

Questions:

  • Is there a way to ensure the child checkboxes become non-selectable in Tom Select when their parent is selected?
  • Am I missing any specific handling in Tom Select to achieve this?

Any suggestions or code modifications are welcome! Thank you in advance.

(No Jquery)

I need to make the rule accept “.” and “,” which does not occur

I'm racking my brain over this. I need this value to allow me to add values ​​like 16.000,00 but when I enter it gives an error or if I enter 16.000 only 16.00 appears on my page

class BidController extends Controller
{
    public function bid(Request $request, $product_id, $slug)
    {
        $product = Product::running()->where('id',$product_id)->firstOrFail();

        if (count($product->bids) > 0){
            $min_amount = getAmount($product->bids->max('bid_amount'));

            $request->validate([
                'amount' => 'required|numeric|gt:'. $min_amount
            ]);
        } else {
            $min_amount = getAmount($product->min_bid_price);

            $request->validate([
                'amount' => 'required|numeric|gte:'. $min_amount
            ]);
        }

I’ve looked everywhere and I can’t figure it out!
I need to create a mask so that the value also appears in this form 000.000,00 which is the value in Brazilian Real

Issues with Firebase Push Notifications on Web and Mobile App

I am currently implementing Firebase for push notifications on both a website and a mobile app. After successful configuration, the push notifications are functioning properly on the mobile app; however, I am encountering issues with the web implementation.

Problems:

Notifications are displaying twice on the web.
Is it possible to expose the notification data publicly for users to inspect?

Here is my Firebase configuration code that i use in script:

var firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "PROJECT_ID.firebaseapp.com",
  databaseURL: "https://DATABASE_NAME.firebaseio.com",
  projectId: "PROJECT_ID",
  storageBucket: "PROJECT_ID.appspot.com",
  messagingSenderId: "SENDER_ID",
  appId: "APP_ID",
  measurementId: "G-MEASUREMENT_ID",
};

I would appreciate any guidance or suggestions on how to resolve these issues.

Thank you!

I have set up Firebase Cloud Messaging (FCM) for both my mobile app and website. After following the official Firebase documentation, I was able to successfully receive push notifications on the mobile app.

Get SVGator Javascript API to work in a timer loop

I have a 4 second SVGator animation that needs to run in it’s entirety, then have the last 2 seconds loop indefinitely. I’ve exported as SVG/Javascript, then used the following JS code…

const element = document.getElementById('eDuWOrNCbmP1');
var player = element ? element.svgatorPlayer : {};

function timerLoop() {
    player.seekTo(2000)();
    setInterval( timerLoop, 2000);
}
if (player.play) {
    player.play();
    setInterval( timerLoop, 4000);  
}

This works fine, but just for one iteration of timerLoop, ie one repetition of the last 2 seconds. After this, it stops working with the JS error…

Uncaught TypeError: player.seekTo(...) is not a function
at timerLoop

Any ideas?

Trying to use Face api to compare a captured image with another one compressed as a base64 that is stored as a string ina json file

Question
I’m working on a project that uses the Face API to compare a live video image with a base64-encoded image. However, when I click the button with the id captureButton, I encounter the following error in the console:

undefined:1 GET http://127.0.0.1:5501/undefined 404 (Not Found) I’m unsure why I’m getting a 404 Not Found error, as I believe my code should be capturing an image from the video stream and comparing it with a base64 image successfully.

Project Context
The goal of my project is to implement a face recognition system that captures images from a video feed (using the device’s webcam) and compares them to a pre-existing image in base64 format. The user can upload an image that is then encoded into base64 format, which I attempt to match against the live video feed to see if they represent the same individual.

Code Overview
Below is the relevant code I’m using, which initializes the Face API, captures a video feed, and sets up the image comparison functionality:

// Funcionalidad api
const base64Image = postData("imagen", {
    dni: dni
});

const video = document.getElementById("video");
const overlayCanvas = document.getElementById("overlayCanvas");
const imageUpload = document.getElementById("imageUpload");
const capturedImage = document.getElementById("capturedImage");
const captureButton = document.getElementById("captureButton");

let uploadedFaceData; // Esto se mantendrá para la imagen subida, si se necesita.
let capturedFaceData;

document.addEventListener("DOMContentLoaded", async () => {
    // Código de inicialización
    console.time("Cargar modelos");
    await faceapi.nets.tinyFaceDetector.loadFromUri("./face-api/models");
    await faceapi.nets.faceLandmark68Net.loadFromUri("./face-api/models");
    await faceapi.nets.faceRecognitionNet.loadFromUri("./face-api/models");
    console.timeEnd("Cargar modelos");
    startVideo();
});

function startVideo() {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
            video.srcObject = stream;
            // Código para manejar el video
        })
        .catch((err) => {
            console.error("Error al acceder a la cámara", err);
            alert("No se pudo acceder a la cámara");
        });
}

captureButton.addEventListener("click", async () => {
    // Código para capturar la imagen del video y comparar
});

Here is my html



<div class="pagina4 pagina flex_center" id="pagina4">

            <div class="contenedor_pagina4 flex_center_evenly">

                <p class="bienvenida_pagina4">Bienvenido/a, (<b id="nombre" class="gradientDCI">nombre</b>)</p>

                <span>Mirá a la cámara!</span>

                <div class="desbloqueo_pagina4 flex_center" id="cara">

                    <div class="camara glass flex_center">

                        <video id="video" autoplay playsinline></video>

                        <img id="capturedImage" style="display: none;"/>

                        <canvas id="overlayCanvas" width="640" height="480" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: block;"></canvas></div>

                    <div class="opciones_camara flex_center_evenly">

                        <button id="captureButton" class="glass button_hover flex_center"></button>

                        <img id="capturedImage" style="display: none;"/>

                        <!-- <button id="compareButton" class="glass"></button> -->

                        <!-- <button id="retry" class="glass"></button> -->

                        <img id="uploadedImage" style="display: none;"/>

                    </div>

                  </div>

                  <input type="file" id="imageUpload" accept="image/*" style="position: absolute; right: 1em; top: 72%;"/>

            </div>

            <div class="contenedor_home_back">

                <button class="home glass button_hover"></button>

                <button id="back4" class="glass button_hover"></button>

            </div>

        </div>


Trouble with routes in CloudWays

i’m having some problems with Node.js Routes on CloudWays application,
I have this example code, and only the root route works ‘/’, the others got a status of 404, how this can be possible, i’m not an expert at Node.js i’m a front-end dev:

import express from "express";
import cors from "cors";
import fetch from "node-fetch";

const app = express();
app.use(cors()); // Habilitar CORS

// Defina seu token de acesso e store ID diretamente no código
const PORT = process.env.PORT || 3000;

app.get('/teste', (req, res) => {
    res.send('<h1>Hello, your Node.js app is running on Cloudways!</h1>');
});


app.get("/produtos", async (req, res) => {
  try {
    const response = await fetch(
      `https://api.tiendanube.com/v1/${storeId}/products`,
      {
        method: "GET",
        headers: {
          Authentication: `bearer ${accessToken}`,
          "Content-Type": "application/json",
          "User-Agent": "Loja ([email protected])",
        },
      }
    );
    if (!response.ok) {
      throw new Error(`Erro: ${response.statusText}`);
    }

    const data = await response.json();
    console.log(data);
    res.json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

const draftOrderData = {
  contact_name: "João",
  contact_lastname: "Paulo",
  contact_email: "[email protected]",
  payment_status: "unpaid",
  products: [
    {
      variant_id: 1048977915, // Substitua pelo ID do produto variante
      quantity: 1, // Propriedades customizadas, se necessário
    },
  ],
};
app.get("/carrinho", async (req, res) => {
  try {
    const response = await fetch(
      `https://api.tiendanube.com/v1/${storeId}/draft_orders`,
      {
        method: "POST",
        headers: {
          Authentication: `bearer ${accessToken}`,
          "Content-Type": "application/json",
          "User-Agent": "Loja ([email protected])",
        },
        body: JSON.stringify(draftOrderData),
      }
    );
    if (!response.ok) {
      throw new Error(`Erro: ${response.statusText}`);
    }

    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  } finally {
    return;
  }
});

app.listen(PORT, () => {
  console.log(`Servidor rodando na porta ${PORT}`);
});

just need that all routes work at the same file, so I dont need to create one code of Node for each route I have just to put it at the root route

How to prevent JavaScript from automatically escaping certain characters?

I have a string of values that I need to transpose to an object. I’ve encountered a weird issue where when the JS code is executed in the browser, it automatically converts certain characters into encoded HTML entities.

The code is as follows:

function split_to_objects(string) {
    var output = {}
    string.split('').reduce(function(object, value, index) {
        output[index] = value;
    }, {})
    return output
}

var input_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstu!"#$%&'(),-./0123456789:;<=>?@[\]^_`';
var output_obj = split_to_objects(input_string);

console.log(output_obj);

This produces the output of:

{
  0: "A",
  1: "B",
  10: "K",
  11: "L",
  12: "M",
  13: "N",
  14: "O",
  15: "P",
  16: "Q",
  17: "R",
  18: "S",
  19: "T",
  2: "C",
  20: "U",
  21: "V",
  22: "W",
  23: "X",
  24: "Y",
  25: "Z",
  26: "a",
  27: "b",
  28: "c",
  29: "d",
  3: "D",
  30: "e",
  31: "f",
  32: "g",
  33: "h",
  34: "i",
  35: "j",
  36: "k",
  37: "l",
  38: "m",
  39: "n",
  4: "E",
  40: "o",
  41: "p",
  42: "q",
  43: "r",
  44: "s",
  45: "t",
  46: "u",
  47: "!",
  48: "&quot;",
  49: "#",
  5: "F",
  50: "$",
  51: "%",
  52: "&amp;",
  53: "'",
  54: "(",
  55: ")",
  56: ",",
  57: "-",
  58: ".",
  59: "/",
  6: "G",
  60: "0",
  61: "1",
  62: "2",
  63: "3",
  64: "4",
  65: "5",
  66: "6",
  67: "7",
  68: "8",
  69: "9",
  7: "H",
  70: ":",
  71: ";",
  72: "&lt;",
  73: "=",
  74: "&gt;",
  75: "?",
  76: "@",
  77: "[",
  78: "",
  79: "]",
  8: "I",
  80: "^",
  81: "_",
  82: "`",
  9: "J"
}

As you can see some characters such as & became &amp; or < became &lt;. So my question is, how can we modify the function to produce the output object values that is identical to the original character like in the string?

node js error 93 ,doenst work the server.js

node:internal/modules/package_json_reader:93
throw error;
^

‘, “nxError: Error parsing C:UsersHarrisonpackage.json: Unexpected token ‘
” is not valid JSON
at parse ()
at read (node:internal/modules/package_json_reader:80:16)
at readPackage (node:internal/modules/package_json_reader:141:10)
at readPackageScope (node:internal/modules/package_json_reader:164:19)
at shouldUseESMLoader (node:internal/modules/run_main:81:15)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:161:24)
at node:internal/main/run_main_module:28:49 {
path: ‘C:UsersHarrisonpackage.json’
}

i wanna solve this trouble

Pause/Play toggle for Lottie playback does not successfully ‘pause’

I am attempting to create a pause/play button ‘toggle’ for Lottie animation playback. The button appearance is provided by Font Awesome icons, defined in javascript to shaw a ‘play’ state when the animation is inactive, and a ‘pause’ state when the animation is active. The ‘play’ behavior appears to work as expected, however, ‘pause’ does not.

The issue does not elicit browser console errors, leading me to think that the EventListener is inadequately defined.

I have tried different methods to define the ‘pause’ javascript, but my code does not successfully stop the Lottie animation from playing.

<!DOCTYPE html>
<html dir="ltr" lang="en">
  <head>
    <title>Lottie Player Web Button Component</title>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0"
    />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.5.3/lottie_svg.min.js"></script>
    <script src="https://kit.fontawesome.com/8a60cdf3a9.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://use.typekit.net/yil7vfv.css">
    <style>
    body {
      font-family: Roboto;
      background: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 40vh;
    }
    .fa-regular {
      color: #666666;
      font-size:30px;
    }
    .my-icon {
        vertical-align: middle;
        font-size: 24px;
    }    
    .my-text {
        font-family: "Courier-new";
    }    
    .my-fancy-container {
        border: none;
        border-radius: 0;
        display: inline-block;
        margin: 60px;
        padding: 10px;
    }
    #play-button {
      padding-right: 16px;
    }
  </style>
</head>
<body>
<div id="lottie-animation" background="transparent"  speed="0.5"  style="width: 400px; height: 400px;"></div>
<div>
  <a href="#" id="playPauseBtn"><i class="fa-regular fa-circle-play"></i></a>
</div>
<script>
// Initialize Lottie player   
      const animation = lottie.loadAnimation({ 
        container: document.getElementById('lottie-animation'),      
        renderer: 'svg',       
        loop: true,       
        autoplay: false, // Set to false to initially not play      
        path: 'https://assets1.lottiefiles.com/datafiles/HN7OcWNnoqje6iXIiZdWzKxvLIbfeCGTmvXmEm1h/data.json' // Replace with your animation file      
      });
      
      // Get buttons
      const playPauseBtn = document.getElementById("playPauseBtn");  
      
      // Play button functionality
      playPauseBtn.addEventListener("click", () => {
        if (animation.pause) {
          animation.play();
          playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-pause"></i>';
        } else {
          animation.pause();
          playPauseBtn.innerHTML = '<i class="fa-regular fa-circle-play"></i>';
        }
      });
    </script>
  </body>
</html>

Route “/[locale]” used `params.locale`. `params` should be awaited before using its properties

I’m working on a Next.js 15 app using the new App Router (app directory) with dynamic route localization. I have a [locale] directory where I handle multiple language routes, and I use the params object to access the locale value. However, I keep getting the following error when trying to access params.locale:

Error: Route "/[locale]" used `params.locale`. `params` should be awaited before using its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis
    at locale (webpack:///app/[locale]/layout.tsx?a262:30:34)

Code Structure
Here’s the structure of my app:

app/
├── [locale]/
│   ├── layout.tsx            // Root layout for [locale] dynamic route
│   └── page.tsx              // Main page component for [locale] dynamic route
locales/
├── en/
│   └── common.json           // English translations
├── lt/
│   └── common.json           // Lithuanian translations
i18Config.js                  // i18n configuration with available locales
i18n.js                       // i18n initialization file
TranslationsProvider.js       // Translation provider component
middleware.js                 // Middleware to handle locale-based redirection

In app/[locale]/layout.tsx, I want to access the locale value from params and pass it to different components. I have tried various ways to access params, but the error persists.

Here’s what my layout.tsx file looks like:

import "@/styles/global.css";
import { Outfit } from "next/font/google";
import { Providers } from "./providers";
import i18nConfig from "../../i18nConfig";
import { dir } from "i18next";

const outfit = Outfit({
  subsets: ["latin"],
  weight: ["300", "400", "500", "600", "700", "800"],
  style: ["normal"],
});

export function generateStaticParams() {
  return i18nConfig.locales.map((locale) => ({ locale }));
}

export default async function RootLayout({
  children,
  params: { locale },
}: {
  children: React.ReactNode;
  params: { locale: string };
}) {
  return (
    <html
      lang={locale}
      dir={dir(locale)}
      suppressHydrationWarning
      className={outfit.className}
    >
      <body className="bg-background">
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

  1. Accessing params directly in the function body: I’ve moved params.locale to a separate constant in the function body, but the error still appears.
  2. Using generateStaticParams: I added generateStaticParams to pre-generate routes for the available locales (en and lt). This didn’t resolve the error either.
  3. Type Adjustments: I created a custom type for params to ensure TypeScript knows the structure of params (i.e., params: { locale: string }).

The error suggests that params should be “awaited,” even though params is an object and not a promise, so await params doesn’t make sense here.
I’ve seen other posts mentioning that destructuring in async functions can cause issues with params in Next.js, but accessing params directly also didn’t work for me.
Restarting the server after every change didn’t resolve the issue either.

How can I correctly access params.locale in a dynamic route layout without getting this error? Is there a workaround or configuration I’m missing? Any insight would be greatly appreciated. Thank you!

Why is valueParser not working in AgGrid v32

I’m using AG-Grid v32.2.1 in a grid where the value of the make column needs to be parsed before going to the server. When I use valueParser as a column setting nothing happens.

Here’s how I’m applying the setting:

<template>
  <AgGridVue
    :rowData="rowData"
    :columnDefs="colDefs"
    :gridOptions="defaultOptions"
    style="height: 500px"
    class="ag-theme-quartz"
    ref="grid"
  />
</template>

<script setup>
import { ref } from "vue";
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-quartz.css";
import { AgGridVue } from "ag-grid-vue3";

const grid = ref(null);
const rowData = ref([
  { make: "Tesla", model: "Model Y", price: 64950, electric: true },
  { make: "Ford", model: "F-Series", price: 33850, electric: false },
  { make: "Toyota", model: "Corolla", price: 29600, electric: false },
]);
const colDefs = ref([
  {
    field: "make",
    cellEditor: "agSelectCellEditor",
    cellEditorParams: {
      values: rowData.value.map((item) => item.make),
    },
    valueParser: (params) => {
      return params.newValue + "[EDITED]";
    },
    editable: true,
  },
  { field: "model" },
  { field: "price" },
  { field: "electric" },
]);

let defaultOptions = {
  domLayout: "autoHeight",
  cellFlashDuration: 250,
  cellFadeDuration: 800,
  defaultColDef: {
    enableCellChangeFlash: true,
  },
};
</script>

Here is an example