How to open a local file in javascript [NOT BROWSER]

I currently have a script that uses LocalStorage for my haxball room.

class HaxStatistics {
    constructor(playerName = '') {
        this.playerName = playerName;
        this.games = 0;
        this.wins = 0;
        this.winrate = '0.00%';
        this.playtime = 0;
        this.goals = 0;
        this.assists = 0;
        this.CS = 0;
        this.ownGoals = 0;
    }
}

function globalStatsCommand(player, message) {
    var stats = new HaxStatistics(player.name);
    if (localStorage.getItem(authArray[player.id][0])) {
        stats = JSON.parse(localStorage.getItem(authArray[player.id][0]));
    }
    var statsString = printPlayerStats(stats);
    room.sendAnnouncement(
        statsString,
        player.id,
        infoColor,
        'bold',
        HaxNotification.CHAT
    );
}

function statsLeaderboardCommand(player, message) {
    var key = message.split(/ +/)[0].substring(1).toLowerCase();
    printRankings(key, player.id);
}

function updatePlayerStats(player, teamStats) {
    var stats = new HaxStatistics(player.name);
    var pComp = getPlayerComp(player);
    if (localStorage.getItem(authArray[player.id][0])) {
        stats = JSON.parse(localStorage.getItem(authArray[player.id][0]));
    }
    stats.games++;
    if (lastWinner == teamStats) stats.wins++;
    stats.winrate = ((100 * stats.wins) / (stats.games || 1)).toFixed(1) + `%`;
    stats.goals += getGoalsPlayer(pComp);
    stats.assists += getAssistsPlayer(pComp);
    stats.ownGoals += getOwnGoalsPlayer(pComp);
    stats.CS += getCSPlayer(pComp);
    stats.playtime += getGametimePlayer(pComp);
    localStorage.setItem(authArray[player.id][0], JSON.stringify(stats));
}

function updateStats() {
    if (
        players.length >= 2 * teamSize &&
        (
            game.scores.time >= (5 / 6) * game.scores.timeLimit ||
            game.scores.red == game.scores.scoreLimit ||
            game.scores.blue == game.scores.scoreLimit
        ) &&
        teamRedStats.length >= teamSize && teamBlueStats.length >= teamSize
    ) {
        for (let player of teamRedStats) {
            updatePlayerStats(player, Team.RED);
        }
        for (let player of teamBlueStats) {
            updatePlayerStats(player, Team.BLUE);
        }
    }
}

function printRankings(statKey, id = 0) {
    var leaderboard = [];
    statKey = statKey == "cs" ? "CS" : statKey;
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        if (key.length == 43)
            leaderboard.push([
                JSON.parse(localStorage.getItem(key)).playerName,
                JSON.parse(localStorage.getItem(key))[statKey],
            ]);
    }
    if (leaderboard.length < 5) {
        if (id != 0) {
            room.sendAnnouncement(
                'Non ci sono ancora abbastanza partite giocate!',
                id,
                errorColor,
                'bold',
                HaxNotification.CHAT
            );
        }
        return;
    }
    leaderboard.sort(function (a, b) { return b[1] - a[1]; });
    var rankingString = `${statKey.charAt(0).toUpperCase() + statKey.slice(1)}> `;
    for (let i = 0; i < 5; i++) {
        let playerName = leaderboard[i][0];
        let playerStat = leaderboard[i][1];
        if (statKey == 'playtime') playerStat = getTimeStats(playerStat);
        rankingString += `#${i + 1} ${playerName} : ${playerStat}, `;
    }
    rankingString = rankingString.substring(0, rankingString.length - 2);
    room.sendAnnouncement(
        rankingString,
        id,
        infoColor,
        'bold',
        HaxNotification.CHAT
    );
}

Since the LDB files are not readable and I cannot currently use a database for economic reasons, I would like to read a local JSON file located in my VPS.
I found a possible solution with FileReader by finding this documentation and tried this solution:

let reader = new FileReader();
reader.readAsText("/home/haxroomie/stats.json");
console.log(reader.result)

Unfortunately it gives me an error and I don’t know how to move anymore… A suggestion?

Make app listen to a dynamically set port – it only listens to the port 3000

I’m trying to make my app listen to another port that I have set dynamically rather than hardcoding the port and I always get an error that the port is already in use

const express = require('express');
const app = express();

app.get('/', (req,res)=>{
 res.send('Hello World!!');
});

app.get('/api/courses', (req,res)=>{
  res.send([1,2,3]);
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

no matter what i set the port to in the terminal it always listens to port 3000

I tried setting the port to anything different than 3000 and it always listens to 3000 unless i change it in the code itself

Does not add the response from the server to the array

I have a function that sends a request to the server to get posts. The response from the server is “200” , but when outputting this array it is empty. I use useEffect so that when I enter the page, it works immediately

import React, { useEffect, useState } from 'react';
import axios from 'axios'


function News() {
    let [post, setpost] = useState([])

    useEffect(()=>{
        getnews()
    }, [])
    
    async function getnews(){
        let responce =  await axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(responce=> setpost(responce.data))
        console.log(post)
    }

    return (<>
        <div className="main">
            <div className="main__name">
                <h1>New</h1>
            </div>
            <div className="main__post">

            </div>
        </div>
    </>);
}
export default News;

enter image description here

How can I use import in background.js in my firefox and chrome extensions?

I’m using vanilla javascript and am doing this at the top of background.js for firefox:

  "background": {
    "scripts": ["scripts/background.js"]
  },

and chrome:

  "background": {
    "service_worker": "scripts/service-worker.js"
  },

In both service-worker.js and background.js I need to use import { thing } from './scripts/utils.js'

How can I do this? I get an error in firefox that says import can only be used at the top of a module.

Automatically scroll down blogger post

I need help about this script. This is automatically scroll down script but the problem is it start scrolling when we click the play button i want it to auto start scrolling when user opens the post..

#abt-scroll{position:fixed;z-index:9999;bottom:0;left:10px;top:380px!important;}

#abt-scroll a{display:block;float:left;width:32px;height:32px;text-indent:-999em; padding: 3px!important;}

#abt-scroll a.abt-scroll{font-family:FontAwesome;border-radius:50%;}

#abt-scroll a.abt-stop{font-family:FontAwesome;margin-left:2px;border-radius:50%;}

#abt-scroll a.abt-stop{background: url(“https://3.bp.blogspot.com/-y7CTiiR2aBU/Wcu4H7AkmtI/AAAAAAAACwM/8mmry5ttOPgCOwJIKIpNM2n_ZyIr95ZngCLcBGAs/s1600/pause.png”);}

#abt-scroll a.abt-scroll{width:33px;height:33px;!important;}

#abt-scroll a.abt-stop{width:34px;height:34px;}

#abt-scroll a.abt-scroll{background: url(“https://1.bp.blogspot.com/-gpimEvetJGo/Wcu2gRFCkiI/AAAAAAAACwA/KIlNSQEG8t0JCw7nwC0cjChy8huaE_TdACLcBGAs/s1600/play.png”);}

function autoScroll(){window.scrollBy(0,1);scrolldelay=setTimeout(‘autoScroll()’,80)}

function stopScroll(){clearTimeout(scrolldelay)}

Play

Pause

how to set default parameters to function in better way

For testing purposes, I wrote a function that generates user objects. The function has parameters with default values, but we can customize it if necessary. User objects may grow large, f.e. these can have 30 properties each, and I don’t want to update function parameters every time plus it looks messy.

Maybe there is better way to do it?

const defaultUser = () => {
  id: uuid(),
  last_time: '17:59:00',
  slide_id: 'slide ID',
  name: 'AA1',
  address: 'blabala',
  number_of_houses: 500,
  age: 20,
  active: false,
  children: {
    boy: [],
    girl: '[]
  },
} 
const generateUSer = ({id:defaultUser.id, last_time=defualtUser.last_time, .....and all the props }={})=>{
return{
id,
last_time,
... and all the props
}
}


const user = generateUSer();
cosnt second_user = generateUSer({name:'test_2'}) 

Issue with canvas straight lines

This canvas have been creating an error since I created it and I haven’t found a solution after all my research. so I need a hand. I need the canvas to create a straight line but it end up creating multiple straight lines from the starting point when the mouse is moving instead of one straight line.

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>

    <style>
        *{
            box-sizing: border-box;
        }

        body,html{
            padding: 0;
            margin: 0;
            height: 100vh;
            width: 100vw;
        }


    </style>
    <body>
       
        <canvas>
            
        </canvas>
        
        <script>
            var colorLine = 'black'
            var fillLine = 'none'
            var prevX = ''
            var prevY = ''
            var isDrawing = false
            var snapshot;
            var canvas = document.querySelector('canvas');
            var ctx = canvas.getContext('2d');

            
            let backgroundSetUp = () => {
                
                canvas.height = window.innerHeight - 50; 
                canvas.width = window.innerWidth - 50;
                ctx.fillStyle = colorLine;
                ctx.fillStyle = fillLine
            };

            let startDrawing = e => {
                isDrawing = true
                
                prevX = e.offsetX 
                prevY = e.offsetY 
                ctx.beginPath();
                ctx.strokeStyle  = 'black'
                ctx.fillStyle = '#fff'
           
            }

            let Drawing = e => {
                if(isDrawing === false)
                return
                ctx.beginPath();
                ctx.moveTo(prevX, prevY);
                ctx.lineTo(e.offsetX, e.offsetY);
                ctx.stroke()

                
            }

            let stopDrawing = e => {
                isDrawing = false
            }






            canvas.onmousedown = ( e => {
                startDrawing(e)
            })
            canvas.onmousemove = ( e => {
                Drawing(e)
            })
            canvas.onmouseup = ( e => {
                stopDrawing(e)
            })

            backgroundSetUp()


        </script>
    </body>
</html>

I want to send the data as it as without removing plus sign or any special character to the PHP page?

Morpho.SmartChip,SCPL.WIN.001,1.0.10,c585b0dc-70d2-4c93-be40-3e1d497a4d1e,MSO1300E2L0SW,MIIEGzCCAwOgAwIBAgIGAYaQ463vMA0GCSqGSIb3DQEBCwUAMIG4MSEwHwYDVQQDDBhEUyBTTUFSVCBDSElQIFBWVCBMVEQgMTkxHjAcBgNVBDMTFVBMT1QgTk8gMSBBIFNFQ1RPUiA3MzEOMAwGA1UECQwFTk9JREExFjAUBgNVBAgMDVVUVEFSIFBSQURFU0gxITAfBgNVBAsMGERJR0lUQUwgU0VSVklDRSBERUxJVkVSWTEbMBkGA1UECgwSU01BUlQgQ0hJUCBQVlQgTFREMQswCQYDVQQGEwJJTjAeFw0yMzAyMjcwMzIxMjVaFw0yMzAzMjkwMzIxMjVaMIHFMRQwEgYDVQQKDAtNQVJQSE9SRFBPQzEMMAoGA1UECwwDRFNBMTEwLwYJKoZIhvcNAQkBFiJwYW5rYWouYWdhcndhbEBzbWFydGNoaXBvbmxpbmUuY29tMQ4wDAYDVQQHDAVOb2lkYTEWMBQGA1UECAwNVXR0YXIgUHJhZGVzaDELMAkGA1UEBhMCaW4xNzA1BgNVBAMMLnJkX2RldmljZV9jNTg1YjBkYy03MGQyLTRjOTMtYmU0MC0zZTFkNDk3YTRkMWUwggEhMA0GCSqGSIb3DQEBAQUAA4IBDgAwggEJAoIBANwvRuuluELXQDiuqzPgUaFTWzH3rlIhJSawRogSbZj/MMHtFi+ZlbAoqPgk9Hvkab0HD2G/Exy6Z5bfEVKq7s43ndiACd7ZQHdIzO//936BwjnPugMPWief7DJa/w0sNlyBlM7DIZX7fjQJboW4bWnw74sGlgykiQ+2i4qj3KfNJuzmFovUSzvp8kfMwAM2kEh8bi89ob+sWkrEmG+gqXAJ1aThIAPcKrds1j62jA7Y+qnPZbBPbuCGidpKysrNgL4TzgO47JFFaKngZmxFpeCrQmxYYTIdzOirXoStTQNi1sMYrgXxquv/OZsKX3Oo42ruOeG0kPZ2yJvMQy/0QdsCAwEAAaMdMBswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAYYwDQYJKoZIhvcNAQELBQADggEBACcT6vR1G7iXwk6qaFZCkjlIu2HFaxTvz9FhS+TpTgKMsxnPXiZYQNfEXe7GLLtvpX54A15/uSUE9Wlo9pCw7aTHr6Eh5FLxZNeYe4pRbWguurI/RVMIthfymvFj0WQtdNunuGiixuM/RxHy1xb9mm2oKquktN/0iy62FX+w53SUCI2MNjdgpDhTdNw61zSb8B1+eAJs0ubFbVe+NektI1+YOw4NBVvL+ODVNzT75ZQwLX93+KPMLbxsATmEvAXFOKWqAKVgVYW91qVPrTL//lyi5jmnBs7vxCFomR4mr2+YTuoIlCfnKHdsd5dNcC3IFGYuwDPiQHPZwJus9TaYq2k=,HZNwrQn15hp3eA2HGYmtapVy1KdD6HyfxyA2sVhSpoX3VDoIt5OL8fueIL9gUlvTn6+qVAwKxJbeCvr+QAD4bhXviM8ksRwVMAUfFwh20aQFkzEd7ghVItGUtfei8Z2u2kA3i2sm0Q+qi3DlBSR1+/zpG1lDssn+JleDdSjY0UQr/C4eVMii0Rpamvqv48sT8TQ0GXZopR1ibqIkkgCgiwHCkQ7cYP+5RWooCd2tNyvpar1PI9DkK4V1dUNgRFTNhf31/UK+tAK9Bd343M3ZqkaufYOjrwYCL+vfLJc5xcufpGlqIEfNXtvD/pypZ1GD27CWriEBXyvWC84iTPspcA==

I am sending this comma seperated values generated in javascript code to php using this ajax code,

$.ajax({
type : "POST",
url : 'BioXml.php',
data : "capturedData="+mydata,
async: true,
success : function(response) {
alert(response);
}
});

But the data I am receiving on php page doesn’t have any plus sign. And to overcome this problem I tried using encodeURIComponent but then it is replacing /,+ all these signs with %2C.

(React-native and firestore) Data resets every time user logs back into the app

The issue I’m facing is that every time a user signs out and logs back in, the mood fieldvalue in my firestore database resets to the ” state instead of the mood data that is previously logged in by the user. I want the pre-existing data to not be reset, but also allow the to add on to the pre-existing data. What would be a method to fix this ?

I have below my code for the parts that is related to the above question.

const HomeScreen = () => {

  const [mood, setMood] = useState('');


  const uid = auth.currentUser?.uid;
  useEffect(() => {
    firestore.collection('Users').doc(uid).get().then((documentSnapshot) => {
      setMood(documentSnapshot.data().mood);
      console.log('set to: '+ uid)
    });
  }, [uid]);

  firestore.collection('Users').doc(uid).update({
    mood,
    stressLevel,
  });

  const handleSignOut = () => {
    auth
      .signOut()
      .then(() => {
        navigation.navigate('Login')
      })
      .catch((error) => {
        alert(error)
      })
    };

        <IconButton  icon={<Icon as={MaterialCommunityIcons} name="emoticon-frown" />} 
        borderRadius= "full"
        _icon={{color: '#ffcb4c', size: 8}} 
        _hover={{bg: 'coolGray.800:alpha.20'}} 
        onPress={() => setMood(firebase.firestore.FieldValue.arrayUnion(
          ''.concat(0,'  ',format(new Date(), "dd/MM/yyyy 'at' h:mm a"))))
                }
        _pressed={{bg: '#ffcb4c',
        _ios: {_icon: {size: "2xl"}}}} 
        _ios={{icon: {size: "2xl"}}} />
        </View>

I tried to troubleshoot and found that removing “mood” from the code below AFTER the usr logs in the data into firebase, keeps the data when the user logs back in. However, the user then is not able to add on to the mood data anymore.

firestore.collection(‘Users’).doc(uid).update({
mood,
stressLevel,
});

how to use StacksEditor?

I want to import StacksEditor to edit my text.

here is my code:

import { StacksEditor } from "@stackoverflow/stacks-editor";
// don't forget to include the styles as well
import "@stackoverflow/stacks-editor/dist/styles.css";
// include the Stacks js and css as they're not included in the bundle
import "@stackoverflow/stacks";
import "@stackoverflow/stacks/dist/css/stacks.css";

new StacksEditor(
    document.querySelector("#editor-container"),
    "*Your* **markdown** here"
);

Succeed to get data, but failed to input to modal form bootstrap with AJAX

Using a bootstrap modal with Ajax and i want to update my data. but there an issue the data doesnt show up to the form , i was trying to use console.log() and i got the data but it failed when i was trying to put to modal form bootstrap
This is the Jquery Code

$(".update-category").click(function (event) {
  const id = $(this).data("id");
  const url = `/Category/GetId?id=${id}`;
  $(".modal-update-category").modal('show');

  $(".modal-update-category").on("shown.bs.modal", function (e) {
    $.ajax({
      method: 'GET',
      url: url,
      contentType: 'application/json',
      success: function (response) {
        $("#categoryName").val(response.categoryName);
        $("#categoryDesc").val(response.description);
      },
      error: function (xhr, status, error) {
        console.log(`Error: ${error}`);
      }
    });
  });
});

and this is the modal..

<div class="modal fade modal-update-category" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div id="liveAlertPlaceholder"></div>
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Insert Category</h5>
            </div>
            <form>
                <div class="modal-body">
                    <div class="form-group row">
                        <div class="col text-center">
                            <label class="col col-form-label fs-6">Category Name</label>
                        </div>
                        <div class="col modal-input ">
                            <input type="text" class="form-control" id="categoryName">
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col text-center">
                            <label class="col col-form-label fs-6">Description</label>
                        </div>
                        <div class="col modal-input">
                            <textarea type="text" class="form-control" id="categoryDesc" style="height: 100px"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary text-light btn-category-submit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

i expect the form can be filled the data

Why the react code leads to infinite loop? why setState when called outside of useEffect causes infinite loop even it is setting to the same value? [duplicate]

why code leads to infinite loop even when value within setState() is not changing.. we know state do not change if the current value and previous values are same. yet state is changing which is leading the component to re-render.

** we know component re-render when state changes

but previous and current values are same

then why component re rendering

also object is not passed as argument where react checks on basis of reference. as this is a primitive react checks on basis of value. still why the component re rendering???

import React, { useState } from 'react'
import logo from './logo.svg'
import './App.css'

function App() {
    const [state,setState] = useState(0)
    console.log(state)
    setState((prev)=>7)
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <p>
                    Edit <code>src/App.jsx</code> and save to reload!
                </p>
                <span className="App-link">Hello from codedamn :)</span>
            </header>
        </div>
    )
}

export default App

setState outside a useEffect totally not equals to useEffect without dependency array. you can try. setState(9) inside a useEffect with no dependency array provided. and setState(9) without useEffect as in the code.