Restrict node.js project to run on a specific server

As our employer demanded to run our node.js project on his own server, we are worried about the files that can be owned and copied to another server (even after obfuscation).

Then is there a way to prevent the JavaScript code from being executed on another system?

My idea is to check some systems information information to know if it’s the right server.

How can this code be adapted to a React JS project ? (animation iOS)

I’m looking to adapt this VanillaJS code into a ReactJS project (iOS application animation).
I’ve been trying for 2 days to do it using best practices, but I can’t…

Here’s the link to the source code that I need to try and reproduce in React JS :

codepen.io/Colir/pen/pooMvzK

This code needs to be adapted in line with React JS best practice.
Please help me, thank you…

Node.js Error: Node is either not clickable or is not an element

I’m just learning to parse and I’ve encountered a problem. I probably misunderstood something or wrote something but I can’t understand what it is

const puppeteer = require(`puppeteer`);

(async () => {
    const browser = await puppeteer.launch({headless:false})
    const page = await browser.newPage()
    await page.goto('https://www.agsvyazi.ru/beeline/numbers/index.page.0.htm',{waitUntil: 'load'})

    let pages = 131;

    let idx = 0;

    const allPhns = [];

    while(pages > idx){

        await new Promise(resolve => setTimeout(resolve, 3000));
        
        let arr = await page.evaluate(() => {

            let elem = Array.from(document.querySelectorAll("div.fl.number-table"), el => el.innerText)
            return elem
        })
        
        allPhns.push(...arr)

        // hrefPer = document.querySelector('div.listing a:last-child').href

        //await page.goto(document.querySelector('div.listing a:last-child').href)

        await page.goto(document.querySelector('div.listing a:last-child').href, {waitUntil: 'load'})

        idx +=1 
    }


    console.log(allPhns)

})()

I tried both page.goto and page.click . I searched a lot in the code of the element, tried querySelector() and querySelectorAll() different “paths”. I don’t understand what the problem is

How to make npm package platform independent

Recently i have created a npm package and i have used #!/usr/bin/env node and in
package.json i have added this line ..
and i have published it into npm but the problem is it works on linux but not in windows..

in package.json
"bin": {
    "haha": "another.js"
  },

So basically now i want to make it both for windows, and linux as well..
i have asked to chatgpt and i follow the instructions but it didn’t work and it even doesn’t work in the linux after follwed of the instructions of chatgpt..

Managing Seat Prices in Gender-Based Seat Assignment: Seeking Solutions for Project Challenges

I am working on a project where I am facing an issue. There is a bus with two seats on each side, and I have assigned names to the seats based on gender, such as ‘male’ or ‘female.’ I want it so that when I click on a male seat, the price increases. However, if I change the gender for the same seat, I want the price to remain unchanged.

if (seatId !== '0') {
  seatNumberSpan.text(seatId);
  updatePrices(seatId, true);
} else {
  updatePrices(seatId, false);
}

function updatePrices(selectedValue, isSelected) {
  // alert(selectedValue)

  alert(isSelected)

  if (isSelected == true) {
    subtotal += seatPrice;
    total += seatPrice;
    input += seatPrice;
  } else {
    subtotal -= seatPrice;
    total -= seatPrice;
    input -= seatPrice;

  }
  // alert(subtotal)
  // Update the HTML content of subtotal and total elements
  $("#subtotal").text(subtotal);
  $("#total").text(total);
  $("#input").val(input);


}

Make Webpack dynamic import reuse a bundled module?

I have separate components for logged in vs logged out people, i.e.:

const AuthRoute = React.lazy(async () => import('routes/AuthRoute'));

const UnauthRoute = React.lazy(async () => import('routes/UnauthRoute'));

export default function HomeRoute() {
  return useAuth() ? <AuthRoute /> : <UnauthRoute />
}

Then, I created separate bundles for auth and unauth, i.e. auth.js:

import './main.ts'; // initialize everything
import 'routes/AuthRoute';

Then I load auth.js or unauth.js based on whether localstorage auth tokens are set. If the auth tokens are invalid, it’ll load auth.js, then make another request to fetch UnauthRoute. If the auth tokens are valid, I expect it to not need to fetch AuthRoute since it’s already in the bundle, but it’s still fetching that file.

Is it possible to configure Webpack to reuse the bundled AuthRoute instead of making another network request when calling import('routes/AuthRoute')?

How do I stream audio from browser mic using JavaScript

My project is a voice-controlled email website. The user has to speak through the browser mic to give in commands. The input audio is expected to not be stored as a file, but instead directly streamed to HuggingFace’s Whisper model Inference API. This model will convert the speech to text, so that further processing can be done. I’ll provide the Inference API JavaScript code below, but I think it expects a file to read instead of a stream. So, I need help modifying this code as well:

async function query(filename) {
    const data = fs.readFileSync(filename);
    const response = await fetch(
        "https://api-inference.huggingface.co/models/openai/whisper-medium",
        {
            headers: { Authorization: "Bearer ...." },
            method: "POST",
            body: data,
        }
    );
    const result = await response.json();
    return result;
}

query("sample1.flac").then((response) => {
    console.log(JSON.stringify(response));
});

So keeping in mind that the audio is to be streamed, how do I record the user’s input from the browser and stream it to HuggingFace?

As of now, I only found the following article the most likely solution:
Building a client-side web app which streams audio from a browser microphone to a server. (Part II)
But this article focuses on the client sending the audio to an intermediate server which was also separately built, and then the server using API calls to Dialogflow.

I need the same functionality, but without the intermediate server and streaming the audio directly to existing server, via HuggingFace’s API call.

how to make a Confirm dialog box program with while loop in Javascript [closed]

I am learning programming and you can say really noob. so I need to make a program with while loop that displays a confirm dialog box with the text “Do you want to continue?” again and again until the user clicks the Cancel button in the dialog box. If the user clicks the OK button in the dialog box, then the program shows an alert dialog box with the text “Hello!”. After the user has closed the alert dialog box the program shows the confirm dialog box again. Now I really don’t understand how can I make it. I know it’s really easy but I just dont know how to do it. I know what while loop is but I don’t know in detail so if anyone can help me please.
I tried many things but nothing worked so I don’t know if any of you can please share something.

Animation for the background makes the website “shake”

I have a problem. I would like to create a kind of animation for falling hearts.
I have linked the code below how it should look like. However, this does not work as expected in React.Js. As soon as the hearts start to fall down the website starts to “shake”. The scrollbar appears horizontally and vertically. In addition, the hearts are not behind the container as they should be.

How can I fix the error so that the hearts behave normally and the website does not start to shake as in the code example below and that they are behind the container?

Please note, that I added inside the index.html the this line

<script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
import React, { useEffect } from 'react';
import './style.css';

const Test= () => {
  useEffect(() => {
    const body = document.querySelector("body");

    const createHeart = () => {
      const heart = document.createElement("div");
      heart.className = "fas fa-heart";
      heart.style.left = `${Math.random() * 100}vw`;
      heart.style.animationDuration = `${Math.random() * 3 + 2}s`;
      body.appendChild(heart);
    };

    const removeOldHearts = () => {
      const heartArr = document.querySelectorAll(".fa-heart");
      if (heartArr.length > 200) {
        heartArr[0].remove();
      }
    };

    const heartInterval = setInterval(createHeart, 100);
    const removeInterval = setInterval(removeOldHearts, 100);

    return () => {
      clearInterval(heartInterval);
      clearInterval(removeInterval);
    };
  }, []);

  return (
    <div className="container">
      <div>
        <h1 className="header_text">Test</h1>
      </div>
    </div>
  );
}


export default Test;
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 90vh;
    /*background-color: #ffffff;*/
    background: pink
}

#noButton {
    position: absolute;
    margin-left: 150px;
    transition: 0.5s;
}

#yesButton {
    position: absolute;
    margin-right: 150px;
}

.header_text {
    font-family: 'Nunito';
    font-size: 40px;
    font-weight: bold;
    color: rgb(0, 0, 0);
    text-align: center;
    margin-top: 20px;
    margin-bottom: 0px;
}

.buttons {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    margin-left: 20px;
}

.btn {
    background-color: #FFB6C1;
    color: white;
    padding: 15px 32px;
    text-align: center;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border: none;
    border-radius: 12px;
    transition: background-color 0.3s ease;
}

.gif_container {
    display: flex;
    justify-content: center;
    align-items: center;
}

@media only screen and (max-width: 320px) and (max-height: 568px) {
    body {
        height: 100vh;
    }

    .header_text {
        font-size: 20px;
    }

    img {
        height: 60vh;
    }

    .btn {
        padding: 10px 18px;
        font-size: 12px;
    }
}

@media only screen and (max-width: 414px) and (max-height: 736px) {
    body {
        height: 90vh;
    }

    .header_text {
        font-size: 28px;
    }

    img {
        height: 60vh;
    }

    .btn {
        padding: 15px 25px;
        font-size: 14px;
    }
}

#container {
    min-width: 30%;
    min-height: 30%;
    backdrop-filter: blur(5px);
    background: rgba(0, 0, 0, 0);
    box-shadow: 5px 5px 5px 2px black;
    border-radius: 20px;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 30px;
    padding: 5px 10px;
    font-family: "Poppins",sans-serif;
}
.fa-heart {
    color: rgb(255, 255, 255);
    font-size: 25px;
    position: absolute;
    animation:  heartMove linear 1;
    top: -10vh;
    z-index: 0;
}

@keyframes heartMove {
    0%{
        transform: translateY(-10vh) ;
    }
    100%{
        transform: translateY(110vh) ;
    }
}

const body = document.querySelector("body");

function createHeart() {
    const heart = document.createElement("div");
    heart.className = "fas fa-heart";
    heart.style.left = (Math.random() * 100)+"vw";
    heart.style.animationDuration = (Math.random()*3)+2+"s"
    body.appendChild(heart);
}
setInterval(createHeart,100);
setInterval(function name(params) {
    var heartArr = document.querySelectorAll(".fa-heart")
    if (heartArr.length > 200) {
       heartArr[0].remove()
    }
    //console.log(heartArr);
},100)
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap');

body{
    background: linear-gradient(45deg,pink,violet);
    width: 100vw;
    height: 100vh;
    margin: 0px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

#container {
    min-width: 30%;
    min-height: 30%;
    backdrop-filter: blur(5px);
    background: rgba(0, 0, 0, 0);
    box-shadow: 5px 5px 5px 2px black;
    border-radius: 20px;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 30px;
    padding: 5px 10px;
    font-family: "Poppins",sans-serif;
}
.fa-heart {
    color: rgb(256, 256, 256);
    font-size: 25px;
    position: absolute;
    animation:  heartMove linear 1;
    top: -10vh;
    z-index: 0;
}

@keyframes heartMove {
    0%{
        transform: translateY(-10vh) ;
    }
    100%{
        transform: translateY(110vh) ;
    }
}
<body>
    <div id="container">
       Test
    </div>
    <script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
</body>

Opening Google AppScript Results in Error

I generated this app script to store likes and dislikes of videos on my HTML website in a Google Sheet. However, each time I open it, it generates the following error:

error screenshot

My code:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Video Liking System')
    .addItem('Initialize Database', 'initializeDatabase')
    .addToUi();
}

function initializeDatabase() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  sheet.clear(); // Clear existing data
  sheet.appendRow(['Video ID', 'Likes', 'Dislikes']); // Add headers
}

function likeVideo(videoId) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var headers = data[0];
  var columnIndex = headers.indexOf('Likes');

  for (var i = 1; i < data.length; i++) {
    if (data[i][headers.indexOf('Video ID')] === videoId) {
      data[i][columnIndex]++;
      sheet.getRange(i + 1, columnIndex + 1).setValue(data[i][columnIndex]);
      return { likes: data[i][columnIndex], dislikes: data[i][headers.indexOf('Dislikes')] };
    }
  }

  return { error: 'Video not found' };
}

function dislikeVideo(videoId) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var headers = data[0];
  var columnIndex = headers.indexOf('Dislikes');

  for (var i = 1; i < data.length; i++) {
    if (data[i][headers.indexOf('Video ID')] === videoId) {
      data[i][columnIndex]++;
      sheet.getRange(i + 1, columnIndex + 1).setValue(data[i][columnIndex]);
      return { likes: data[i][headers.indexOf('Likes')], dislikes: data[i][columnIndex] };
    }
  }

  return { error: 'Video not found' };
}

I have tried recreating this code on multiple different scripts, sheets, and accounts, but they all result in this error, which makes me believe this is an error being caused by something in the code, that I can’t identify. It also says to wait and come back, which I have done for days.

Is there a way to create a new image from some text and another image, in js?

<body id="slshow_body" style="text-align: center;" >
<h2>Add new sliding image</h2>
<img name="simage1" id="simage1" src=""/>
<br>
<br>
<a href="http://localhost:3000" type="button" class="homepg-btn">Çıkış/Ana sayfa</a>
<script>
    window.addEventListener('load', () => { 
        simage1.src = "http://127.0.0.1:3000/Brother TN-1040 toner.png";
        simage1.appendChild("Brother TN-1040 toner");
        simage1.appendChild("Price: $100");
    })    
</script>    

Hello js gurus. I’d like to put some text and a picture together to create a new picture in js. I tried using appendChild method as shown in my attached code but I can’t get it to work. When I run the code, all I get is simage1 picture without the text that I want to append. Any help will be appreciated. Thanks.

Unable to pass the last few tests in spite of getting the app fulfill all the criteria mentioned in the test suite

I’m working on the freeCodeCamp’s 25+5 clock project. Though the app works as expected from the functional pov still I’m unable to pass the remaining 4-5 tests in the test suite.

Link to the project

Relevant portion of the code for the application:

interval;
  constructor(props) {
    super(props);
    this.state = {
      breakLength: 5,
      sessionLength: 25,
      timer: 1500,
      timerType: "Session",
      timerState: "stopped"
    };
  }

  componentDidMount() {
    this.setState({
      breakLength: 5,
      sessionLength: 25,
      timer: 1500,
      timerType: "Session",
      timerState: "stopped"
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.timer === 0 && prevState.timerType === "Session") {
      this.setState({
        timer: prevState.breakLength * 60,
        timerType: "Break"
      });
    } else if (prevState.timer === 0 && prevState.timerType === "Break") {
      this.setState({
        timer: prevState.sessionLength * 60,
        timerType: "Session"
      });
    }
  }

  breakDecrement = () => {
    if (this.state.breakLength < 2) return;
    this.setState((prevState) => ({
      breakLength: prevState.breakLength - 1
    }));
  };

  breakIncrement = () => {
    if (this.state.breakLength > 59) return;
    this.setState((prevState) => ({
      breakLength: prevState.breakLength + 1
    }));
  };

  sessionDecrement = () => {
    if (this.state.sessionLength < 2) return;
    this.setState((prevState) => ({
      sessionLength: prevState.sessionLength - 1,
      timer: prevState.timer - 60
    }));
  };

  sessionIncrement = () => {
    if (this.state.sessionLength > 59) return;
    this.setState((prevState) => ({
      sessionLength: prevState.sessionLength + 1,
      timer: prevState.timer + 60
    }));
  };

  startTimer = () => {
    this.interval = setInterval(() => {
      this.setState(
        (prevState) => ({ timer: prevState.timer - 1, timerState: "start" }),
        () => {
          if (this.state.timer === 0) {
            this.buzzer();
            this.stopTimer();
            this.startTimer();
          }
        }
      );
    }, 1000);
  };

  stopTimer = () => {
    clearInterval(this.interval);
  };


  toggleTimer = () => {
    if (this.state.timerState === "stopped") {
      this.startTimer();
    } else if (this.state.timerState === "start") {
      this.stopTimer();
    }

    this.setState((prevState) => ({
      timerState: prevState.timerState === "stopped" ? "start" : "stopped"
    }));
  };

  resetTimer = () => {
    this.stopTimer();
    this.setState({
      breakLength: 5,
      sessionLength: 25,
      timer: 1500,
      timerType: "Session"
    });
    this.audioBeep.pause();
  };

  buzzer = () => {
    if (this.state.timer === 0) {
      this.audioBeep.play();
    }
  };

  clockify = () => {
    const { timer } = this.state;
    if (timer < 0) return "00:00";

    let minutes = Math.floor(timer / 60);
    let seconds = timer - minutes * 60;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    return minutes + ":" + seconds;
  };

Three out of five failed tests(12,14,1,) throw this ‘Timer has not reached 00:00.’, but the timer does reach 00:00 (you can check that out for yourself). Can’t point out which part of the code is causing this problem.

The app fulfills all the required criteria in application but still I can’t passs the remaining 4-5 tests in the test suite. I sense a few more amends will do the thing but I’ve been unable to figure them out so far.
What can I do to pass the remaining tests in the test suite?

DataTable export to PDF + asynchronously images = double files exported

I’m using DataTable and I have code that works basically fine. After clicking the button responsible for exporting table to PDF, a file with images is generated and downloaded, everything is great. The problem is (probably) that it happens asynchronously and two files are actually downloaded. One ‘file-correct’ with graphics and one ‘file-invalid’, without graphics. How can I change this so that only the correct file is downloaded? I removed some of the code for clarity.

I tried to add the code to live.datatables.net (https://live.datatables.net/noguvana/1/edit) but a lot of errors appear and the actual file-correct is not downloaded at all. It’s strange, because these errors don’t appear in the browser at all (in console) when I have the code on my site and the file-correct is exported (unfortunately with the file-invalid one).

I will mention that my programming knowledge is not so good. My code, I feel like it’s sometimes a zombie product, which I put together and glue together from various code examples from the DataTable forum and Stack Oveflow.

document.addEventListener('DOMContentLoaded', function() {
  
    const dataTable = $('#myTable').DataTable({
        buttons: [{
            extend: 'excel',
        }, {
            extend: 'pdf',
            title: 'file-invalid',
            async customize(doc) {
                if (doc) {
                    const fetches = [];
                    let imagesFetched = 0;

                    for (let i = 1; i < doc.content[1].table.body.length; i++) {
                        if (doc.content[1].table.body[i].length >= 6) {
                            const imageSrcElement = doc.content[1].table.body[i][5].text;
                            const parser = new DOMParser();
                            const docHTML = parser.parseFromString(imageSrcElement, 'text/html');
                            const imageSrc = docHTML.body.querySelector('img').getAttribute('src');

                            const data = await fetchImage(imageSrc);
                            doc.content[1].table.body[i][5] = {
                                alignment: 'center',
                                image: data,
                                width: 60,
                            };
                            imagesFetched++;
                        }
                    }

                    await Promise.all(fetches);
                    pdfMake.createPdf(doc).download('file-correct.pdf');
                }
            }
        }],
    });

    function fetchImage(url) {
      return new Promise((resolve, reject) => {
        fetch(url)
          .then(response => response.blob())
          .then(blob => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(blob);
          })
          .catch(reject);
      });
    }

    document.getElementById("export-pdf").addEventListener("click", function() {
        dataTable.button(1).trigger();
    });
       
});

Redirecting to a new page after loading a json file does not work

I’m working on a project with Angular. I would like to let the user load a json file that was previously saved via my site. After the data has been successfully loaded, the user should then be directed to another page.

This is the loading function:

onFileSelected(event: any): void {
    const file = event.target.files[0];
    if (file) {
      this.dataService.resetAllData()
      const fileReader = new FileReader();
      fileReader.readAsText(file, 'UTF-8');
      fileReader.onload = () => {
        try {
          const json = JSON.parse(fileReader.result as string);
          this.allData = json;
          console.log('JSON-Daten geladen:', this.allData);
          this.dataService.setAllData(this.allData);
          window.location.href = "/planung";
        } catch (e) {
          console.error('Fehler beim Parsen der JSON-Datei:', e);
        }
      };
      fileReader.onerror = (error) => {
        console.error('Fehler beim Lesen der Datei:', error);
      };
    }
  }

Without the line “window.location.href = “/planung”;” it all works great. With the line the redirect works, but without loading the Data. It seems as if the data appears briefly but then disappears after being forwarded.

What mistake did I make?