Unexpected result while creating a child_process

I am trying to call a function from an external file using child_process, but, it is returning to me an unexpected message and doesn’t even run the target function.

index.ts

import { fork } from 'child_process';

var cards = fork(`${__dirname}/workers/shuffleCards.js`, []);
cards.on("message", msg => { console.log(`Received message`, msg) });
cards.on("error", msg => { console.log(`Received error`, msg) });
cards.send("test");

shuffleCards.js

import cardShuffler from "../components/cardShuffler";

function shuffleCards() {
    const pid = process.pid;
    console.log(`Received process: ${pid}`);

    var action_cards = cardShuffler.shuffleActions();
    var property_cards = cardShuffler.shuffleProperties();
    var money_cards = cardShuffler.shuffleMoney();
    var rent_cards = cardShuffler.shuffleRent();
    var wild_cards = cardShuffler.shuffleWilds();

    var parsed_cards = [];
    [action_cards, property_cards, money_cards, rent_cards, wild_cards].map(card => {
        card.forEach(sub_card => {
            parsed_cards.push(sub_card)
        });
    });

    console.log(parsed_cards)

    return parsed_cards;
}

process.once("message", shuffleCards);

Message on console.log

Received message {
  compile: 'C:\Users\USER\source\repos\Will\src\components\cardShuffler.ts',
  compiledPath: 'C:\Users\USER\AppData\Local\Temp\.ts-nodeeyTUFf\compiled\src_components_cardShuffler_ts_7ae359b0420e1268f12c87be4bf028cb159f9cb115715422295351cb6494e318.js'
}

So it is returning me this compile and compiledPath message and it does not execute the shuffleCards() function

Reached heap limit Allocation failed – JavaScript heap out of memory on discord.js

I am trying to run a discord bot that doesn’t have too many features but it keep sending me this error message. I tried using node --max-old-space-size=4096 index.js but my computer keeps slowing down every time I run it, and my replit code editor website fails to run the code, and prints out Killed when I used node --max-old-space-size=8192 index.js. The part that encounters the error is trying to create 3 discord channels in a category. I am not sure if that in it of itself is causing the issue, or if by that point my program has already been struggling.
Any idea on how to fix this?

The error message:

<--- Last few GCs --->

[100:0x4531d40]    74195 ms: Mark-sweep 513.7 (515.1) -> 513.7 (515.6) MB, 2922.5 / 0.0 ms  (average mu = 0.124, current mu = 0.024) allocation failure scavenge might not succeed
[100:0x4531d40]    77190 ms: Mark-sweep 514.2 (515.6) -> 514.2 (516.4) MB, 2980.1 / 0.0 ms  (average mu = 0.062, current mu = 0.005) allocation failure scavenge might not succeed


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x140dc19]
Security context: 0x24a99db008d1 <JSObject>
    1: night [0x3f7b0f409d99] [/home/runner/Mafia-Bot/src/main/index.js:~129] [pc=0x13cfd4cdd9bc](this=0x229449502949 <JSGlobal Object>,0x2033d497ff11 <Base map = 0x3920bdef45a9>)
    2: /* anonymous */ [0x31c43b433119] [/home/runner/Mafia-Bot/src/main/index.js:64] [bytecode=0xe2cd5da74f9 offset=403](this=0x1195a81019a1 <EventEmitter map = 0x3920bded4a29>,0x2033d...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xa1a640 node::Abort() [node]
 2: 0xa1aa4c node::OnFatalError(char const*, char const*) [node]
 3: 0xb9a62e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xb9a9a9 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xd57c25  [node]
 6: 0xd582b6 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xd64b75 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xd65a25 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xd684dc v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
10: 0xd2eefb v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
11: 0x10714ce v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x140dc19  [node]
Aborted (core dumped)

How can I use innerText instead of innerHTML in dynamically created HTML elements?

I use Javascript to dynamically create a lot of elements. Divs, images, spans, etc.

Here is an example piece of code that my JS would run:

infoCell.innerHTML = "Submitted by " + "<a href='/user/" + this.poster + "'><img src='" + this.poster_avatar_src + "' class='avatarimg'>  <span style='color:blue'>" + this.poster + "</span> </a>in " + "<span style='color:blue; font-weight: 900;'><a href='/h/" + href + "'>" + this.topic + "</a></span>"

This was written early in my JS development, but now I realize that it can very quickly become very insecure, as almost all of the javascript variables being inserted into the HTML are written by the user with no limitations to character usage, etc.

How can I go through my javascript and change all of these so they still function, but without worrying about users inserting script into my site?

I am fine rewriting a lot but I would like to not do this again. I have about 90 innerHTML DOM modifications in my main JS file (typescript).

Could you explain me this freecodecamp recursion function, please?

Here’s the code

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

I understand that until startNum equals endNum it will recall itself, but the thing that I don’t understand is where the value is stored?

Say for example it’s rangeOfNumbers(3,6)
So it’s gonna be like this:

6-1
5-1
4-1

Right? And each time the numbers are added to the array and we get [3,4,5,6], but I don’t understand how and where it stores this array.

If I’m not mistaken, concat merges two or more arrays, but there are no arrays.

I just want to have a full understanding of it. Otherwise, I won’t remember it and won’t be able to use it.

Appearing/disappearing element using ‘style.display’ not working

So I thought it would be pretty simple to implement an if statement to have an element appear or disappear at the click of a button.
After a couple of hours now, I have not gotten further than getting the element to disappear. It registers the second click(tested with a console.log), but the display property does not change back to ‘flex’.

I’ve also already tried different variations of ‘getElementById’ and ‘querySelector’ during my sentence.

const edit = document.getElementById('edit-btn');
const fill = document.querySelector('#filler');

edit.addEventListener('click', popInOut(fill))

function popInOut(e){
    if(e.style.display=='flex'){
        e.style.display='none'
    }else if(e.style.display=='none'){
        e.style.display='flex'
    }
}

The ‘filler’ element is a bootstrap column with this styling.

#filler{
    display:flex;
    flex-direction: column;
    background-color: #1c1f22;
    position:absolute;
    top:40%;
    height:50%;
}

How to secure a no-authentication game leaderboard?

I making a online quiz game (SPA web application) and I want to implement a leaderboard with the player’s score. I’m sending a request with the player’s initials and score to my back-end (REST API). Problem is that anybody could see the request to the REST API, in the network tab, and send a similar request from Postman. How do you secure such a leaderboard? There is no authentication – you just type in 3 symbols (your initials) just like in arcade games.

I’m using ExpressJS with MongoDB for the API.

“GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)” error

Google thinks that I am trying to read data from localhost:8801, but I am trying to read that data from another file called “main.js.” The error is “GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)” How can I reference the command from main.js without google thinking that it is a subdirectory. Here is my code in index.html:

https://sourceb.in/iuMyon5XI7

Thank you in advance.

405 Method Not Allowed – Axios

I am trying to get a user’s email and save it to a database without refreshing the page using Axios but, I keep getting a 405 error. Also, I am trying to connect to my localhost using post from postman api and I am getting a 405 error as well.

Html:

<form id="emaildata" action="" method="POST" role="form">
              <input type="email" name="email" id="joinme" placeholder="Email:">
              <input type="submit" value="Subscribe">
</form>

JS/Axios:

 (function() {
      "use strict";
      document.getElementById("emaildata").addEventListener("submit", function(e) {
        e.preventDefault();
        let email = document.getElementById("joinme").value;
    
        const emailData = new FormData();
        emailData.append('email', email);
        emailData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    
        axios.post('http://127.0.0.1:8000', emailData) // 4
          .then(res => alert("Form Submitted")) // 5
          .catch(errors => console.log(errors)) // 6
      });
    })()

Postman:405 Error

Google apps script function work in backend but called by javascript responds undefined

Ok, this is my function.

.gs
function createIfNotExistSheet( name = 'Controller Settings' ) {
  var resp = "";
  try {
    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var newSheet = activeSpreadsheet.getSheetByName(name);

    if (newSheet == null) {
      newSheet = activeSpreadsheet.insertSheet();
      newSheet.setName(name);
    }
    resp = "Sheet "+ name +" are ready, at id = "+ newSheet.getSheetId();
  }
  catch (e) {
    resp = e;
  }
  finally{
    Logger.log(resp);
    return resp;
  }
}

I call it from js with:

js.
settingsFile = google.script.run.createIfNotExistSheet(cC.settingsFile['name']);

Whether I call it with or without the argument the result does not change, settingsFile returns undefined.

export css file to be available through a url

I have the following scenario.

Two independent node projects need to have the same css colouring. My idea is that I have a custom.css in my public folder of my node project, and another node project would be able to consum this file over a link. For example, if my node project runs on localhost:3000, my idea is that the css file would be available by localhost:3000/custom.css.

Does anybody has an idea how to do that?

I am looking for a way to implement such a link to export the css.

Thanks in advance

JavaScript Image Collision Detection

Ok. So, I’m trying to find out when 2 images collide in a game I made, but I’ve been receiving conflicting advice and I’m not exactly sure how to get any of the solutions to work (as all of them result in errors, and the collision results as null)

here are the two options I’ve been trying to solve (any solution works really, I’m just stumped and can’t seem to get it to work regardless of what I try).

  // first option
  function trackXY(){
        for(let i=0; i<2; i++){
          let playerrr = document.getElementById('moveAva');
          let pikaTest = document.getElementById('pikaLocation' + i);
          
          let playHeight = window.getComputedStyle(playerrr).getPropertyValue('height');
          let playWidth = window.getComputedStyle(playerrr).getPropertyValue('width');
          let playLeft = window.getComputedStyle(playerrr).getPropertyValue('left');
          let playTop = window.getComputedStyle(playerrr).getPropertyValue('top');

          let pokeHeight = window.getComputedStyle(pikaTest).getPropertyValue('height');
          let pokeWidth = window.getComputedStyle(pikaTest).getPropertyValue('width');
          let pokeLeft = window.getComputedStyle(pikaTest).getPropertyValue('left');
          let pokeTop = window.getComputedStyle(pikaTest).getPropertyValue('top');
          let xPlayer = parseInt(playLeft + .5*playWidth);
          let yPlayer = parseInt(playTop + .5*playHeight);
          let xEnemy = parseInt(pokeLeft + .5*pokeWidth);
          let yEnemy = parseInt(pokeTop + .5*pokeHeight);
          let rPlayer = .5*parseInt(playHeight);
          let rEnemy = .5*parseInt(pokeHeight);
          let dX = xEnemy - xPlayer;
          let dY = yEnemy - yPlayer;
          let distance = Math.sqrt((dX*dX)+(dY*dY))
          if(distance <= (rEnemy+rPlayer)){
              alert("collison!");
              playHeight = parseInt(playHeight) + .5*parseInt(pokeHeight);
              document.getElementById('pikaInvent').style.display = "block";
              document.getElementById('pikaWon').style.display = "block";
          }
        }
      }
     //second option
     function trackXY(){
        for(let i=0; i<1; i++){
            let playerrr = document.getElementById('moveAva');
            let pikaTest = document.getElementById('pikaLocation' + i);


        let xPlayer = parseInt(playerrr.style.left + .5*playerrr.style.width);
        let yPlayer = parseInt(playerrr.style.top + .5*playerrr.style.height);
        let xEnemy = parseInt(pikaTest.style.left + .5*pikaTest.style.width);
        let yEnemy = parseInt(pikaTest.style.top + .5*pikaTest.style.height);
        let rPlayer = .5*parseInt(playerrr.style.height);
        let rEnemy = .5*parseInt(pikaTest.style.height);
        let dX = xEnemy - xPlayer;
        let dY = yEnemy - yPlayer;
        let distance = Math.sqrt((dX*dX)+(dY*dY))
        if(distance <= (rEnemy+rPlayer)){
            alert("collison!" + enemy.id);
        }
      }
    }
trackXY();

if anyone could help, I could really appreciate it. Or, if you have another solution for collision detection with 2 rectangular images. Thanks!

Binance API {“code”:-1022,”msg”:”Signature for this request is not valid.”}. Not sure what I am doing incorrectly

I’m not sure what is wrong with this code. I think I might be missing something somewhere but I can’t figure it out. I keep getting the error

const ts = Date.now()

var crypto = require('crypto')
                  , text = 'recvWindow=59999&timestamp=ts' 
                  , key = 'BqDjQf3F5VNOvSaX1rncMsZqmSOpGTBPz5UgOohto0P3bQlfHvjUlVrkbYc6pwc3'
                  , hash;

var hash = crypto.createHmac('sha256', key).update(text).digest('hex');


[hash, key, ts.toString()];

Clear completed task button To-do list

I have tried to create a code that clear all completed task (completed task which is the items with a line-through on them) when the clear completed button is clicked. I will leave the function open as I’m open to new ideas and you should run code snippet to better understand the question.thanks

var addButton = document.getElementById("add_button");
var ul = document.querySelector("ul");
var input = document.getElementById("entry_box");
var clearBtn = document.getElementById("clear");
var saveBtn = document.getElementById("save");
var emptyBtn = document.getElementById("empty");


function newToDoItem() {
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
}

function inputLength() {
  return input.value.length;
}

function addToDoItem() {
  if (inputLength() > 0) {
    newToDoItem();
  }
}

function keyPressEvent(event) {
  if (inputLength() > 0 && event.keyCode === 13) {
    newToDoItem();
  }
}

function toggleToDoItemState(event) {
  if (event.target.tagName === "LI") {
    event.target.classList.toggle("done");
  }
}


addButton.addEventListener("click", addToDoItem);
//clearBtn.addEventListener("click", clearCompletedToDoItems);
ul.addEventListener("dblclick", toggleToDoItemState);
input.addEventListener("keypress", keyPressEvent);
*{
    
    padding: px0;
    margin: px0;
}
body{
    width:100%;
    display:-webkit-box;
    -webkit-box-pack:center;
    
    
}

#big_wrapper{
    text-align: center;
    max-width:1000px;
    margin:20px 0px;
    display:-webkit-box;
    background: rgb(201, 207, 214);
    -webkit-box-orient: vertical;
    -webkit-box-flex:1;
    border-radius: 20px;

}
#big_wrapper{
      width:1000px;
    
}
#position{
    padding: 20px;

}
ul {
    cursor: pointer;
}

.done {
    text-decoration: line-through;
}
<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="utf-8" />
    <title>erand boy</title>
    <link rel="stylesheet" href="todo.css" />
  </head>
  <body>
    <div id="big_wrapper">
      <div id="position">
        <header>
          <h1>My to-do list</h1>
          <p>wirte the list of things you need to do here.</p>
        </header>
        <div>
          <input type="text" id="entry_box" />
          <button id="add_button">Add</button>
          <p><strong>Double click an item to mark it complete.</strong></p>
          <ul id="toDolist" style="text-align: left"></ul>
        </div>
        <div id="button_wrapper">
          <button id="save">Save list</button>
          <button id="clear">Clear completed</button>
          <button id="empty">Empty list</button>
        </div>
      </div>
    </div>
    <script src="to-do.js"></script>
  </body>
</html>

Thrheybsh