Web Development – Seeking a Solution for Video Slicing to Upload Segments to Server

In the course of a web development project, I encountered a challenge with video slicing for efficient uploading to a server. Initially, I developed a service that successfully sliced MP4 files by extracting bytes from one point to another. However, I’ve encountered an issue during the merging process after uploading the segmented videos. The videos fail to merge successfully, and I’m seeking insights and solutions to overcome this hurdle.

In my attempts to address the issue, I’ve reviewed the video slicing process and implemented various approaches. Despite these efforts, the merging of the segmented videos still poses a problem. I expected a seamless merging process after uploading the segmented parts, but unfortunately, that hasn’t been the case. However, I’ve come to realize that video slicing involves more complexity, as outlined in this insightful Stack Overflow post.

If anyone has experience with video slicing, especially in the context of web development, and has successfully tackled similar merging challenges, I would greatly appreciate your guidance. Additionally, if you have recommendations for packages or libraries that handle video slicing and merging effectively, please share your insights.

Lost leading newline characters when getting value from a textarea

I want to pass a string variable from PHP to javascript, I tried the third method in this answer, but I when I got the value (textarea.value) from the textarea, I lost the leading newline characters.

I tried to add a character like “=” at the beginning and the end of my string, it seems that I solved this problem. Are there any ways better to deal with this problem? Are there any other problems which can cause I getting different value that I may encounter?

PHP code:

<textarea id="data"><?php echo htmlspecialchars("nna"); ?></textarea>

javascript code:

let a=document.getElementById("data").value;
// expect: "nna"
// actual: "na"

Pinia state initialized with async function but only after component is mounted

I’m using Pinia and Vue.js 3 to display a list of products in a page.
However, when I use my product store in my component, all I see in the page is loading. Only when I go to another pages and come back to the products page, is when I see that my products are gotten from the store and listed in the page. Which, I guess, it means that the component is mounted and everything before the store has initialized the state from the async function.

Here is the code:

Pinia Store
enter image description here

Component
enter image description here

Thank You!

DOM manipulation from an async JS

I need some help with async javascript and DOM manipulation.

More precisely I am using revive adserver on my website and need to change a zoneid in the adserver tag if consent is given by a cookie manager.

(data-revive-zoneid=”1″ shows only local stored ads | data-revive-zoneid=”2″ shows externals ads like google after given consent)

With my old cookie manager from klaro (NOT IN ASYNC MODE!) that was working great and reliable:

<ins data-revive-zoneid="1" data-revive-id="xxx" id="add_above"></ins>
<script>
  if (klaro.getManager().consents.gadsense) {
    document.getElementById("add_above").setAttribute("data-revive-zoneid", 2);
  }
</script>
<script async src="/adserver/www/delivery/asyncjs.php"></script>

The new cookie manager from clickio works completely in async mode. Using the following code, I have the problem, that sometimes after given consent the data-revive-zoneid=”1″ changes to “2” and sometimes stays “1” (seen with the shown ads and console.log). If the zoneid does not change to 2, I can see with console.log that getElementById(“add_above”) is null.

<ins data-revive-zoneid="1" data-revive-id="xxx" id="add_above"></ins>
<script async type="text/clickiocmp" data-clickio-cmp-vendor-consent="755">
  document.getElementById("add_above").setAttribute("data-revive-zoneid", 2);
</script>
<script async src="/adserver/www/delivery/asyncjs.php"></script>

The same problem with JQuery

<ins data-revive-zoneid="1" data-revive-id="xxx" id="add_above"></ins>
<script async type="text/clickiocmp" data-clickio-cmp-vendor-consent="755">
  jQuery( document ).ready(function($) {$('#add_above').attr( 'data-revive-zoneid','2');});
</script>
<script async src="/adserver/www/delivery/asyncjs.php"></script>

What can I do to change the DOM element “data-revive-zoneid” reliable from the async javascript <script async type="text/clickiocmp" data-clickio-cmp-vendor-consent="755"></script>.

Tinymce image upload handler optimization

I have written an image upload script for tinymce, but was wondering if it could be optimized in any way? It seems to work pretty well, but I believe there is room for improvements. How it works is pretty simple, png, jpeg, jpg, bmp are all resized to 800px x 800px if they have larger dimensions. I found gifs were more problematic to work with, so instead of resizing them I thought it would be best to limit the file size which could be uploaded instead, then allow the original file to be uploaded.

tinymce.init({
    selector: 'textarea#comment',
    plugins: 'media preview link emoticons help insertdatetime table anchor wordcount visualblocks image code',
    toolbar: 'undo redo | media | image | blocks | ' + 'bold italic backcolor forecolor | alignleft aligncenter ' + 'alignright alignjustify | outdent indent removeformat',
    content_css: '/css/styling.css',
    media_live_embeds: true,
    media_poster: false,
  menu: {
    file:  { title: 'File', items: 'print' },
    edit:  { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' },
    view: { title: 'View', items: 'visualaid  visualblocks preview wordcount code' },
    insert: { title: 'Insert', items: 'table inserttable | cell row column | advtablesort | tableprops deletetable | emoticons link anchor media image | hr | insertdatetime' },
    format: { title: 'Format', items: 'bold italic underline strikethrough | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | removeformat' },
    table: { title: '', items: '' },
    tools: { title: '', items: '' },
    help:  { title: 'Help', items: 'help' },
  }, 
    block_unsupported_drop: true,
    paste_data_images:false,
    image_title: true,
    images_file_types: 'jpg,png,gif,jpeg',
    file_picker_types: 'image',
    file_picker_callback: function(cb, value, meta) {
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.setAttribute('name', 'photos');
        input.addEventListener("change", (event) =>  {
            let FILE = event.target.files[0];
            var fTypes = ["jpg", "png", "gif", "jpeg", "bmp"];
            filename = FILE.name.substring(FILE.name.lastIndexOf('.') + 1, FILE.name.length) || FILE.name;
            if (fTypes.indexOf(filename) == 2) {
                var fileSizeLimit = 0.1;
                if (FILE.size > fileSizeLimit * 1024 * 1024) {
                    alert(" Error! Image is too large, maximum file size allowed is 100kb");
                    return null;
                }
            }
            if (fTypes.indexOf(filename) > -1) {
                let reader = new FileReader;
                reader.readAsDataURL(FILE);
                reader.onload = (event) => {
                    let image_url = event.target.result;
                    let image = document.createElement("img");
                    image.src = image_url;
                    image.onload = (e) =>  {
                        var MAX_WIDTH = 800;
                        var MAX_HEIGHT = 800;
                        var width = e.target.width;
                        var height = e.target.height;
                        if (width > height) {
                            if (width > MAX_WIDTH) {
                                height = height * (MAX_WIDTH / width);
                                width = MAX_WIDTH;
                            }
                        } else {
                            if (height > MAX_HEIGHT) {
                                width = width * (MAX_HEIGHT / height);
                                height = MAX_HEIGHT;
                            }
                        }
                        let canvas = document.createElement("canvas");
                        canvas.width = width;
                        canvas.height = height;
                        const context = canvas.getContext("2d");
                        context.drawImage(image, 0, 0, canvas.width, canvas.height);
                        let new_image_url = context.canvas.toDataURL();
                        let new_image = document.createElement("img");
                        new_image.src = new_image_url;
                        doBlob();
                        async function doBlob() {
                            const base64Response = await fetch(new_image.src);
                            const blob = await base64Response.blob();
                            let obj = '';
                            if (fTypes.indexOf(filename) == 2) {
                                obj = FILE;
                            }else{
                                obj = blob;
                            }
                            var id = 'xxxblobid' + (new Date()).getTime();
                            var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                            var base64 = new_image.src.split(',')[1];
                            var blobInfo = blobCache.create(id, obj, base64);
                            blobCache.add(blobInfo);        
                            cb(blobInfo.blobUri(), {
                                title: FILE.name,
                                imageSize: canvas.width * canvas.height,
                                maxSize: canvas.width * canvas.height
                            });
                        }
                    }
                }
            } else {
                alert('Sorry, we only allow, jpg, png, gif or jpeg files, Please choose another file to upload.');
                return null;
            }
        });
        input.click();
    },
    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
});

I am sure this code could be improved for better performance. This is my first attempt at meddling with tinymce’s editors because I could not find a good image upload script for it.

how to convert Excel file to JSON with JS5 rhino script?

I’m making a bot for some messenger. This bot uses things like ‘onNotificationPosted’ to read notifications from the messenger and responds using the quick reply function provided by the messenger. So, rather than using an external server or running the program on a computer, I am running a bot program using an app called ‘Messenger Bot R’.

So, it is impossible to import an external library using npm, but it is possible to download the file directly and load the module with ‘require’.

I’m Korean, but there aren’t many materials like this in Korea. Unfortunately, this bot uses Rhino JavaScript, which only supports JS5, so I can’t search for the necessary functions in English.

So I want to ask a question, even if it means using a translator. Can I write code to load the Excel file in my phone as JSON? I cant use nodeJS TT

I searched Google diligently.

nestjs how can i use any-exception.filter catch code error

I try to use the any-exception.filter to catch errors, but i find anothor error. When the any-exception.filter caught an error, i want to res.json to the client, But at this point, because the interface request was successful, so the transform.interceptor will next.handle().pipe some data to client, it make another error msg(Cannot set headers after they are sent to the client), pls how can i fix it???

// any-exception.filter.ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { CustomLoggerService } from 'src/modules/logger/logger.service';
import { getReqMainInfo } from 'src/utils/tools';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly logger: CustomLoggerService) {}

  catch(exception: unknown, host: ArgumentsHost) {
   
    const ctx = host.switchToHttp();

    const response = ctx.getResponse<Response>();

    const request = ctx.getRequest<Request>();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const exceptionResponse: any =
      exception instanceof HttpException ? exception.getResponse() : undefined;
    let validatorMessage = exceptionResponse;
    if (typeof validatorMessage === 'object') {
      validatorMessage = exceptionResponse.message;
      if (validatorMessage instanceof Array) {
        validatorMessage = validatorMessage.join(',');
      }
    }

    const message =
      exception instanceof HttpException
        ? exception.message
          ? exception.message
          : 'Service Error'
        : 'Service Error';

    if (exception instanceof HttpException) return;

    const info = getReqMainInfo(request, response);

    const logFormat = `
      Method:${info.method},
      Status code: ${status},
      Request original url: ${info.url},
      Query: ${JSON.stringify(info.query)},
      Body: ${JSON.stringify(info.body)},
      IP: ${info.ip},
      Host: ${info.host},
      Msg: ${message},
      SysErrorMsg: ${exception}`;

    this.logger.error(logFormat);
    console.log(exception);
    console.log(111);

    response.status(status).json({
      code: status,
      result: null,
      msg: validatorMessage || message,
      success: false,
      path: request.url,
      timestamp: new Date().getTime(),
    });

    return;
  }
}
// transform.interceptor.ts
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map } from 'rxjs';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      map((res) => {
        console.log(2222);
        return {
          code: 200,
          result: res.data,
          msg: res.msg ? res.msg : '请求成功',
          success: true,
          timestamp: new Date().getTime(),
        };
      }),
    );
  }
}

// console.log msg: TypeError: Cannot destructure property 'statusCode' of 'res' as it is null.
    at getReqMainInfo (/Volumes/ProjectDocuments/myProduct/callis-blog-server/src/utils/tools.ts:22:11)
    at LoggerMiddleware.use (/Volumes/ProjectDocuments/myProduct/callis-blog-server/src/middlewares/logger.middleware.ts:15:32)
    at /Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/router/router-proxy.js:9:23
    at Layer.handle [as handle_request] (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:144:13)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:140:7)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:140:7)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:140:7)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:140:7)
    at next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/router/route.js:140:7)
111
2222
Error: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:400:5)
    at ServerResponse.setHeader (node:_http_outgoing:663:11)
    at ServerResponse.header (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:278:15)
    at ExpressAdapter.reply (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/platform-express/adapters/express-adapter.js:62:62)
    at RouterResponseController.apply (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/router/router-response-controller.js:15:36)
    at /Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/router/router-execution-context.js:175:48
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at /Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/router/router-execution-context.js:47:13 {
  code: 'ERR_HTTP_HEADERS_SENT'
}
111
Error: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:400:5)
    at ServerResponse.setHeader (node:_http_outgoing:663:11)
    at ServerResponse.header (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/express/lib/response.js:278:15)
    at AllExceptionsFilter.catch (/Volumes/ProjectDocuments/myProduct/callis-blog-server/src/filter/http-exception/any-exception.filter.ts:67:29)
    at ExceptionsHandler.invokeCustomFilters (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/exceptions/exceptions-handler.js:30:26)
    at ExceptionsHandler.next (/Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/exceptions/exceptions-handler.js:14:18)
    at /Volumes/ProjectDocuments/myProduct/callis-blog-server/node_modules/@nestjs/core/router/router-proxy.js:13:35
    at processTicksAndRejections (node:internal/process/task_queues:95:5) 

How to pdate state value of array in React

I have two API which returns json data. In my state variable I have an empty array. I want to append those json data in my empty array when I call useefect.

This is my Context.

const AppContext = createContext()
const urls = ['api/load-all-news/0/20', 'api/load-all-news/20/20']


const initialState = {
    allNews: [],

    
}

const AppProvider=({children})=>{
    const [state, dispatch] = useReducer(reducer, initialState);


     
    const getAllNews = async(url)=>{
      try{
        const res = await fetch(url)
        const data = await res.json()
        
        dispatch({ type: "ALL_NEWS", payload: data.news_list})
      }catch(err){
        console.log(err)
      }
    }
    
       useEffect(()=>{
          for(let i=0; i<urls.length;i++){
            getAllNews(urls[i])
          }
       },[])
  
    
    return<AppContext.Provider value={{...state}}>{children}</AppContext.Provider>
}

const useGlobalContext=()=>{
    return useContext(AppContext)
}

export {AppContext, AppProvider, useGlobalContext}

This is my Reducer

const Reducer = (state, action) => {

  if (action.type === "ALL_NEWS") {
     
   const {allNews} =  state
  

    return {
      ...state,
     allNews: [...allNews, action.payload]
    };
  }
    return state;
}

export default Reducer;

My final allNews array should be [Array(20), Array(20)] . Arrays from two API. but Its showing [Array(20), Array(20), Array(20), Array(20)]. How to solve this issue.. please tell me where I am doing wrong.

React image from public folder not loading in Docker

I am running a Node server and React frontend in Docker. They have a shared volume, specifically for the /public folder. At Docker build time, the only relevant picture in the /public folder is “output1.png”.

During runtime, the server receives images and writes them to the volume, e.g. “input1.png”.

I can see both of these files (input1.png, output1.png) in the docker filesystem for both containers: , and when I pull input1.png off of the docker volume, it’s a valid image (in fact, it is the same image as output1.png).

However, when I go to show these images in React, output1.png shows up but input1.png does not. I’m not that familiar with webdev, but another data point that might be helpful is that localhost:3000/output1.png shows an image whereas localhost:3000/input1.png does not. I’m wondering if this is an issue with using Docker, like maybe only files that are there during the build are valid in the javascript runtime considered?

Server image saving code:

//  a zmq subscriber that reads from zmq and publishes over websocket to react.
//  react apps can't directly read from zmq, so we need to use this server to bridge the gap.

// zmq subscriber initialized here
var zmq = require("zeromq"),
  sock = zmq.socket("sub");

// ws server initialized here to send data to react
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 6002 });
let currentData = {};

let count = 0;
sock.bindSync(`tcp://*:6001`, (err) => { // bind fails because we don't wait for bind or smth, bindSync works
  if (err) throw err;
  console.log(`ZeroMQ publisher bound to port 6001`);
});sock.subscribe("");
console.log("Subscriber connected to port 6001");

sock.on('message', function(message) {
    try {
        count += 1;
        currentData = JSON.parse(message);
        const image_count = { type: 'image_count', value: count };
        currentData.push(image_count);
        wss.clients.forEach(function each(client) {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(currentData));
            }
        });
        const fs = require('fs');
        const imageObject = currentData.find(item => item.type === 'composite_image');
        const image_rcvd = Buffer.from(imageObject.image, 'base64');
        const filename = `public/input${count}.png`;
        fs.writeFile(filename, image_rcvd, function(err) {
          if (err) {
            console.log('Error:', err);
          } else {
            console.log('Image saved');
          }
        });
        currentData = currentData.filter(item => item.type !== 'composite_image'); // Remove the "composite_image" object
        console.log(currentData);
    } catch (error) {
        console.error('Error parsing ZMQ message:', error);
    }
});

// ws server connection
wss.on('connection', function connection(ws) {
    console.log('WebSocket client connected');

    ws.on('close', function close() {
        console.log('WebSocket client disconnected');
    });
});

console.log("WebSocket server started on ws://0.0.0.0:6002");

Relevant image placing code (leaflet map):

if (imageData.image_count !== 0) {
      console.log("adding image");
      let filename = process.env.PUBLIC_URL + "/input" + imageData.image_count + ".png";
      console.log(filename);
      try {
        let overlay = L.imageOverlay.rotated(filename, imageData.topleft, imageData.topright, imageData.bottomleft).addTo(map);
        console.log(overlay);
      } catch (error) {
        console.log(error);
      }

React dockerfile:

# react
FROM node:14
WORKDIR /app


COPY package.json .
COPY package-lock.json .

RUN npm install
RUN npm install -g serve

COPY . .
RUN npm run build
# server on 3001
EXPOSE 3001
CMD ["serve", "-s", "build", "-l", "3001"]

Node server dockerfile:

# server
FROM node:14
WORKDIR /app


COPY package.json .
COPY package-lock.json .

RUN npm install

COPY . .
RUN npm run build

CMD ["node", "server.js"]

Why my dynamoDB table items are deleted when doing loops over batchwriteItems?

I’ve a javascript code which saves schedules in a dynamoDB table. To do this i’ve a loop which writes all scheduled day in the table. For this i’ve created a loop with batchWriteItems (also with a normal mutation createSchedule) and whatever i do, the planning is full of wholes, and many days are not saved in the table.

Also when i try to launch the process a second time, it will delete items that were already in the table. I’m never able to save all items correctly, there is always a network error.

I’ve no error on AWS side.

It’s only working very well when i select like 60 days max (so 60 items to write) but more than this will produce the described issue.

Any idea on why this is happening and what to do ?

I’ve tried with normal mutations and then batchWriteItem but it’s the same.

My throughput is not limited, i pay on the go.

TypeScript throws error even after declared types are found in @types/morgan

I am developing an express application in NodeJS and using the morgan middleware for logging. I am writing the code using typescript and have installed the required types for express, morgan and node.
Whenever I try to compile the code to commonjs file, it throws the following error:

Argument of type 'string' is not assignable to parameter of type 'FormatFn<IncomingMessage, ServerResponse<IncomingMessage>>'

The code for my morgan middle ware setup is like:

app.use("*", morgan(":remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms", {
    skip: function (req: Request, res: Response) { return res.status < 400 }
}));

I tried removing the options object, it works fine then but I need to filter some logs from my console otherwise it will be flooded. On my manual inspection of @types/morgan, I found the relevant declaration of

declare function morgan<
    Request extends http.IncomingMessage = http.IncomingMessage,
    Response extends http.ServerResponse = http.ServerResponse,
>(
    format: string,
    options?: morgan.Options<Request, Response>,
): Handler<Request, Response>;

But this is not being considered while compilation for some reason, I guess.

Filter database from json to JS

I am trying to filter only the last 24 hour data from the json file. Here is what I did but i dont get anything anything in my chart. I am missing something?

  .then((response) => response.json())
  .then((data) => {
    console.log("Fetched data:", data);

    // Filter data for the last day (last 24 hours)
    lastDayData = data.filter((entry) => {
      const entryDate = new Date(entry.createdAt);
      const twentyFourHoursAgo = new Date();
      twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24);

      return entryDate >= twentyFourHoursAgo;
    });

    // Format timestamps using moment.js (or adjust as needed)
    const formattedDates = lastDayData.map((entry) =>
      moment(entry.createdAt).format("YYYY-MM-DD HH:mm:ss")
    );``

how to redirect to other ejs from script of one ejs file with arguments

i created a room using socket.io and want to send the meassage from one ejs file to the other

    function joinRoom() {
        let roomCode = document.getElementById('roomCode').value;
        if (roomCode) {
          console.log(roomCode);
          socket.emit("pvt-room",roomCode);
          roomCode="";
        }
      }

      socket.on("pvt-msg",(msg)=>{
        window.location.href = '/chat';
      })

here is the server side code

    app.get("/", (req, res) => {
      res.render("room.ejs");
    });

    app.get("/chat", (req, res) => {
      res.render("chat.ejs");

    });

    io.on("connection", (socket) => {
      console.log("a user connected");
      socket.on("pvt-room", (roomNo) => {
      socket.join(roomNo);
       io.to(roomNo).emit("pvt-msg", "welcome to private room");
     });
   });

i tried sending the data from one ejs file to the other ejs file through the script tag of the first ejs file. But not able to parse the url data at the server side

Adding up the total value in array JS? [duplicate]

Trying to solve how to add up the total value of an array.

example:

const arr = [23, 5, 8];
// output 36

This works however, but what I have trouble with is passing an existing array into my .forEach loop. Have a look…

My JS:

// my array to get all prices in the shopping cart.
var totalPrice = [];

// function to get numbers
const addNumbers = (card) => {
    const { price } = getCardInfo(card);
    var currency = price;
    var number = Number(currency.replace(/[^0-9.-]+/g,""));

    // add to array 
    totalPrice.push(number);

    // sum up values in array 
    const arr = [23, 5, 8];
    // const arr = totalPrice[]???
    let sum = 0;
    arr.forEach((el) => sum += el);
    console.log("Sum of Numbers: " + sum);


    console.log("Number: " + number);
    console.log("Total Price: " + totalPrice);
};

Everytime I click on a product card, this function runs, and it will push a new price to the array var totalPrice = [];.

How do I get the sum of the number values in my pre-existing array? Thanks!