Where can I run Nodejs code instead of on my local computer?

So I have the following skeleton code written in nodejs:

            function getData(){
                //some code to retrieve data
            }

            function processData(){
                let dataList = getData();
            
               dataList.forEach(e => {
                //perform some computation
               });
            }

            processData();    //processData is a very resource intense function call.

My question here is, is there a place where I can deploy this code to run instead of my local computer? This code may take hours if not days to complete.

How to store fetch headers in javacript from website I don’t own?

I am trying to save headers when a specific fetch is completed on a website I do not own. This is so I can complete a new fetch that requires variables inside the headers that are specific to different users. I found this:

window.fetch = new Proxy(window.fetch, {
    apply(actualFetch, that, args) {
        // Forward function call to the original fetch
        const result = Reflect.apply(actualFetch, that, args);

        // Do whatever you want with the resulting Promise
        result.then((response) => {
            console.log("fetch completed!", args, response);
        });

        return result;
    }
});

But it only seems to work in the browser console. I’m trying to get it working in a chrome extension.

Here’s what I’ve added to the code. Not none of the logs appear in the console. My version works in the browser console as well just not when used in an extension I’m writing.

window.fetch = new Proxy(window.fetch, {
            apply(actualFetch, that, args) {
                console.log('fetchingworking')
                // Forward function call to the original fetch
                const result = Reflect.apply(actualFetch, that, args);

                // Do whatever you want with the resulting Promise
                result.then((response) => {
                    if (args[0].includes('page%22%3A') && args[0].includes('nrte') == false) {
                        console.log('fetchinfoworking')
                        fetchinfo = {
                            urlstart: args[0].split('page%22%3A')[0] + 'page%22%3A',
                            urlend: '%7D%7D&extensions' + args[0].split('%7D%7D&extensions')[1],
                            fetchhead: args[1].headers,
                        }
                    }
                });

                return result;
            }
        })

Aligned Divs not aligning properly

Im building a 3D render for JavaScript and the first feature I need is a X , Y mouse display. This display is a paragraph tag which is in a div which should be aligned. right next to each other.

I’ve tried changing the div width, margin, padding, float, align but it just doesn’t seem to work.

let renArea = document.querySelector("#render");
let cc = renArea.getContext("2d"); //cc for canvas contenxt.

//Pre-Display
document.querySelector("#postion-display").innerHTML = "Put mouse on canvas.";

//Get mouse (X, Y) and siplay it for user refrence. 
function getMousePosition(canvas, event) {
    let rect = canvas.getBoundingClientRect();
    let x = event.clientX - rect.left;
    let y = event.clientY - rect.top;
    document.querySelector("#postion-display").innerHTML = "Coordinate x: " + Math.round(x) + " Coordinate y: " + Math.round(y);
}

renArea.addEventListener("mousemove", function (e) {
    getMousePosition(renArea, e);
}); 


cc.moveTo(0, 0);
cc.lineTo(200, 100);
cc.stroke();
html, body {
    margin: 0px;
    margin-top: 5vh;
}

.wrapper {
    margin: 0px;
}

.header {
    position: fixed;
    padding: 1px;
    width: 100%;
    top: 0;    
    padding-left: 12px;
    background: lightcoral;
}

.render-area {
    margin: 0px;
}

canvas {
    border: 2px solid black;
    float: right;
    margin-right: 10px;
}
<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Render | Js</title>

        <link rel="stylesheet" href="media/global.css">
    </head>
    <body>
        <div class="wrapper">
            <div class="header">
                <h3>Render | Js</h3>
            </div>

            <div class="editor" style="width: 50%; float: left;">
                <p id="postion-display"></p>
            </div>
            <div class="render-area" style="float: left; width: 50%;">
                <canvas width="500" height="500" id="render"></canvas>
            </div>
        </div>

        <script src="./src/render.js"></script>
    </body>
</html>

I am coding a command that once ran would allow me to check the servers a user is in, however I am getting an error

const {
  InteractionType,
  GatewayIntentBits,
  EmbedBuilder,
} = require("discord.js");
const { Client } = require("discord.js");
const { SlashCommandBuilder } = require("@discordjs/builders");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, clientId, guildId } = require("../../config.json");

const client = new Client({
  intents: Object.keys(GatewayIntentBits).map((a) => {
    return GatewayIntentBits[a];
  }),
});

const commandData = new SlashCommandBuilder()
  .setName("checkuserguilds")
  .setDescription("Check the guilds a user is in")
  .addUserOption((option) =>
    option
      .setName("user")
      .setDescription("The user to check the guilds for")
      .setRequired(true)
  );

const allowedRoleName = "DOW Directors"; // Replace 'YOUR_ALLOWED_ROLE_NAME' with the name of the role allowed to run the command

client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}!`);

  const rest = new REST({ version: "9" }).setToken(token);

  try {
    console.log("Started refreshing application (/) commands.");

    await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
      body: [commandData.toJSON()],
    });

    console.log("Successfully reloaded application (/) commands.");
  } catch (error) {
    console.error(error);
  }
});

const execute = async (interaction) => {
  if (interaction.type === InteractionType.ApplicationCommand) {
    if (interaction.commandName === "checkuserguilds") {
      if (!checkPermission(interaction.member)) {
        return interaction.reply({
          content: "You do not have permission to run this command.",
          ephemeral: true,
        });
      }

      const user = interaction.options.getUser("user");
      if (!user) {
        return interaction.reply({
          content: "Please specify a user.",
          ephemeral: true,
        });
      }

      try {
        const guilds = await getUserGuilds(user.id);
        const embed = new EmbedBuilder()
          .setColor("#0099ff")
          .setTitle("User Guilds")
          .setDescription(
            `User ${user.tag} is in the following guilds:n${guilds.join("n")}`
          );
        await interaction.reply({ embeds:  });
      } catch (error) {
        console.error("Error fetching user guilds:", error);
        await interaction.reply("Error fetching user guilds.");
      }
    }
  }
};

function checkPermission(member) {
  return member.roles.cache.some((role) => role.name === allowedRoleName);
}

async function getUserGuilds(userId) {
  try {
    const user = await client.users.fetch(userId);
    const userGuilds = client.guilds.cache.filter((guild) =>
      guild.members.cache.has(user.id)
    );
    return userGuilds.map((guild) => guild.name);
  } catch (error) {
    console.error("Error fetching user guilds:", error);
    return [];
  }
}

module.exports = {
  data: commandData,
  execute,
};

I have tried to reset my tokens, and I am still receiving the “Error fetching user guilds: Expected token to be set for this request, but none was present.” I have configured the code to where I am not just handing out the token in all the commands. so it is centrally located in the config.json file.

Ethereum: how to generate a valid address from the public key?

I am using this code to generate a private key, public key and address, acording to this:

The public key is generated from the private key using the Elliptic Curve Digital Signature Algorithm. You get a public address for your account by taking the last 20 bytes of the Keccak-256 hash of the public key and adding 0x to the beginning.

const { secp256k1 } = require("ethereum-cryptography/secp256k1");
const { keccak256 } = require("ethereum-cryptography/keccak");
const { toHex } = require("ethereum-cryptography/utils");

const privateKey = secp256k1.utils.randomPrivateKey();
console.log('private key :  ', toHex(privateKey));

const publicKey = secp256k1.getPublicKey(privateKey);
console.log('public key  :', toHex(publicKey));

const address = keccak256(publicKey.slice(1)).slice(-20);
console.log('address     :', '0x' + toHex(address));

However, I get a valid private and public key pair, but not the corresponding address (compared to some online converters like this and this).

Why is my AJAX form refreshing the page when I submit?

I am creating a simple Follow/Unfollow system, everything works fine in the sense that it inserts the row and deletes the row when I follow/unfollow, but for some reason it refreshes the page every time, even though I’m using e.preventDefault();, why is this? Thanks

<?php if ($is_following): ?>
   <form method="POST" action="">
     <input type="hidden" value="<?php echo $username; ?>" name="username">
     <input type="hidden" value="<?php echo $grabUser['username']; ?>" name="following">
     <input type="hidden" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
     <button class="followBtn" type="button" value="unfollow" name="action">Unfollow</button>
   </form>
 <?php else: ?>
   <form method="POST" action="">
     <input type="hidden" value="<?php echo $username; ?>" name="username">
     <input type="hidden" value="<?php echo $grabUser['username']; ?>" name="following">
     <input type="hidden" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
     <button class="followBtn" type="button" value="follow" name="action">Follow</button>
    </form>
 <?php endif; ?>

This is my script at the bottom of my webpage:

  <script type="text/javascript">
  //~~~~~~~~~~~~~~~~~~~~ SCRIPT FOR FOLLOWING A USER ~~~~~~~~~~~~~~~~~~~~//
  (function() {
    $(document).ready(function() {
    console.log("Follow function is working..");
    $(".followBtn").on("click", function(e) {

        if ($(this).hasClass('followBtn-signin')) {
            e.preventDefault(); // Prevent form submission
            $('#loginModal').modal('show'); // Show login modal
            return;
        }

        e.preventDefault();

        var followButton = $(this);
        var formDataFollow = {
            'FollowUser': true,
            'username': $(this).siblings('input[name="username"]').val(),
            'following': $(this).siblings('input[name="following"]').val(),
            'date': $(this).siblings('input[name="date"]').val(),
            'action': $(this).val()
        };
        console.log(formDataFollow);
        $.ajax({
            type: "POST",
            url: "/Blog/resources/PHP/FollowUserPHP.php",
            data: formDataFollow,
            dataType: 'json',
            success: function(response) {
                // Toggle the button text based on the response
                if (response.status === "followed") {
                    followButton.text("Unfollow");
                } else if (response.status === "unfollowed") {
                    followButton.text("Follow");
                }
                // Manually submit the form
                followButton.closest('form').submit();
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
      });
    });
   })();
 </script>

and this is my FollowUserPHP.php:

 <?php
  session_start();
  require_once '/var/www/vhosts/my-site.xyz/httpdocs/PHP/connect.php';

 if (isset($_POST['username']) && isset($_POST['following']) && isset($_POST['date']) && isset($_POST['action'])) {
  $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
  $following = filter_var($_POST['following'], FILTER_SANITIZE_STRING);
  $date = filter_var($_POST['date'], FILTER_SANITIZE_STRING);
  $action = $_POST['action'];

if ($action == 'follow') {
    $stmt = $dbh->prepare("INSERT INTO `followers` (`username`, `following`, `date`) VALUES (:username, :following, :date)");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':following', $following, PDO::PARAM_STR);
    $stmt->bindParam(':date', $date, PDO::PARAM_STR);
    $stmt->execute();
    $response = array('status' => 'followed');
} elseif ($action == 'unfollow') {
    $stmt = $dbh->prepare("DELETE FROM `followers` WHERE `username` = :username AND `following` = :following");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':following', $following, PDO::PARAM_STR);
    $stmt->execute();
    $response = array('status' => 'unfollowed');
} else {
    // Invalid action value
    $response = array('error' => 'Invalid action');
}
} else {
// Missing parameters
$response = array('error' => 'Missing parameters');
}

// Output the response as JSON
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>

How to display only cities names in Satellite view (google maps api)

I can’t control the lables display in satellite or hybrid view, but it work well when I not specific mapTypeId.

The styles not take effect if that mapTypeId is in satellite or hybrid.

Any help, thanks

  // Request needed libraries.
  const { Map, InfoWindow } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
    "marker",
  );
  const map = new Map(document.getElementById("map"), {
    zoom: 12,
    center: { lat: 34.84555, lng: -111.8035 },
    mapTypeId: 'satellite',
    disableDefaultUI: true,
    mapId: "4504f8b37365c3d0",
    // Disable various map features to only show city names.
    styles: [
    
    
      {
        featureType: "all",
        elementType: "labels",
        stylers: [{ visibility: "off" }],
      },
      {
        featureType: "administrative",
        elementType: "labels",
        stylers: [{ visibility: "on" }],
      },
      {
        featureType: "administrative.locality",
        elementType: "labels",
        stylers: [{ visibility: "on" }],
      },
    ],
  });

I tried to add disableDefaultUI: true,
but it doesn’t work

How do I trigger onclick event with only one click?

It’s me again! I’ve been slaving to get an accordion menu to work properly and I managed to get it to work… the main problem is, it only triggers on the double click of a button.

I want to make this so the user only needs to click on the button once. I have other usages of buttons in my code that work with only one click and this one does follow their formats, but I don’t know whats making it trigger only on double click.

Here is the Javascript — I could only make it work if i put it in a function(), just leaving out the function would not allow the script to work.


function accordion() {

const acc = document.getElementsByClassName("levelTab");
var a;

for (a = 0; a < acc.length; a++) {
    acc[a].addEventListener('click', function() {
        this.classList.toggle('active');
        var levelContain = this.nextElementSibling;
        if (levelContain.style.maxHeight) {
            levelContain.style.maxHeight = null;
        } else {
            levelContain.style.maxHeight = levelContain.scrollHeight + "px";
        }
    });
};
}

And the HTML


<button onclick="accordion()" class="levelTab">Cantrips</button>
                <div class="levelContain">
                    <p>
                        insert Spells here.
                    </p>
                </div>

scrape a JS-Rendered, JSON using R

I want to get the info stored in some JQuery scripts

link <- "https://rod.pulse.gop.pk/details_page.html?I=740287512"
webpage <- xml2::read_html(link)

In the above link it only shows partial data but what I want to get is the json file with full data stored in some link inspect > network > _search

https://rodb.pulse.gop.pk/registry_index_2/_search

below is the data stored in the above link

{"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"registry_index_2","_id":"740287512","_score":1.0,"_source":{"Id":740287512,"UserId":13887,"VendorId":1,"UserWorkQueMasterId":740237089,"RegisteredNumber":"310","JildNumber":"1489","PropertyNumber":"واقع رقبہ  موضع سوہان دیہاتی  اندر حدود  میونسپل کارپوریشن راولپنڈی تحصیل و ضلع راولپنڈی ","IsApproved":true,"IsJildCompleted":false,"BahiNumber":null,"RegistryDate":"1993-01-25","IsActive":true,"CreatedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"TehsilId":112,"MauzaId":0,"Address":"N/A","IsExported":null,"Area":"0-8-0-0","RegistryValue":128000.0,"RegistryExportImg":"cfe958064b6c79b71e03350b5394f32a","NonNullFCount":null,"NullFCount":null,"RegistryTypeId":5,"MauzaName":null,"RegistryParties":[{"Id":18595212,"Name":"محمد یسین ","SpouseName":"شمس الدین ","CNIC":"21134087515","RegistryPartiesTypeId":1,"CraetedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"VendorId":1,"SequenceNumber":1,"RegistryExportImg":"b17f19516a4fc8742aa21ce8bf0340b4"},{"Id":18595213,"Name":"چوہدری رحمت ","SpouseName":"چوہدری الله دین ","CNIC":"0","RegistryPartiesTypeId":2,"CraetedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"VendorId":1,"SequenceNumber":2,"RegistryExportImg":"89c79a6b93dde25904088ce129b1a22a"}],"RegistryType":"بیع","Tehsil":"راولپنڈی"}}]}}


library(jsonlite)
lines <- readLines("_search.json")
lines[1] <- sub(".* = (.*)", "\1", lines[1])
lines[length(lines)] <- sub(";", "", lines[length(lines)])
json_data <- fromJSON(paste(lines, collapse="n"))
head(json_data[[4]][[3]])

The above data is publicly available data

Get SVG Path Point Position Relative to DOM (not parent SVG)

I am trying to do a motion path of an image, that will jump from 1 SVG to another, following all paths.
The image is a normal

What I want is to move the image to a specific point, on any svg I have in my document.
If I add my image inside a SVG (using svg image) and move it, it’s easy, I just use:

var temp_point=temp_path.getPointAtLength(temp_distance);
$('.handz').css("transform","translateX("+temp_point.x+"px) translateY("+temp_point.y+"px) rotate("+deg+"deg)");

But since I want to have my image outside the svg, and have 1 single image, that can be moved to any point on any path, from any svg from my document, I can’t seem to figure it out.

I tried using:

function getRelativeXY(x, y, svg, element){

  var xx=element.getBoundingClientRect().x+x;
  var yy=element.getBoundingClientRect().y+y;
  return {x:xx,y:yy}
}

But it does not give me the desired results, as it does not move precisely where it should move. I think (I am not sure) it has something to do if the original svg has scaling/transforms applied, or different view box details.

enter image description here

Open random .html file when pressing Shuffle button

My problem is that i have already made implementation of java script Shuffle button but only working in specific url which i will put into line document.location.href i used for this example somefile.html.

    jQuery('body').on('click', '#shuffle-button', function() {
        gtag('event', 'Shuffle', {
            'click': 'true'
        });
        ga('send', 'event', 'Shuffle', 'click', 'true');
        document.location.href = '**/somefile.html**';
    }).on('click', '#station-share-toggle, #station-share-close', function() {
        $('#station-share-buttons').toggle();
    }).on('click', '.jp-share-button', function() {
        window.open($(this).attr('href'), "share", "width=500, height=500");
        return false;
    });

So into same folder where is located somefile.html there is 350+ other .html files which i would like to make it when Shuffle button is clicked to transfer to random of that 350+ .html files.
This example only work for somefile.html. What i have to do to or where is my mistake I would be glad if someone has option to make it functional.

Next.JS / Clerk.com and authentication with .net Web API

I’m new to react/next.js and I’m trying to setup my app to use a backend .NET 8 WEB API.

I have my WEB API set up via this Link.

This works great. When I start my WEB API in VS 2022, then it requires me to sign into Clerk.com and then displays my WEB API call.

Now I’m trying to call the same WEB API via my next.js app.

In the end, I would want the user to sign into my next.js app, then use that sign in validation to pass to my .NET 8 WEB API to log into that and then be able to talk properly to the WEB API.

Right now, I have to make sure I am signed out of the WEB API, then sign into next.js via Clerk.com. Then click the button that calls the WEB API and it requires me to sign in AGAIN to Clerk.com.

After this is done it receives a 302 found. Seems like it isn’t passing across the necessary items to do the authentication?

enter image description here

Any thoughts?

Here is my next.js code:

"use client"

import { useEffect, useState } from 'react';
import { WeatherForecast } from '../interfaces/WeatherForecastModel'; // Adjust the import path as necessary

import { enableRipple } from '@syncfusion/ej2-base';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons'
import { useAuth, useClerk } from '@clerk/clerk-react'
enableRipple(true);

const Index = () => {
  const { getToken } = useAuth()
  const [token, setToken] = useState(''); // Manage token with useState
  const [clerkOther, setclerkOther] = useState(''); // Manage token with useState
  const [data, setData] = useState<WeatherForecast[]>([]);

  const { user } = useClerk();

  const fetchData = async (url: string) => {
    const token = await getToken();
    const clerkOther = user?.publicMetadata.clerk_token as string;
    setToken(token ?? ''); // Update the token state
    setclerkOther(clerkOther); // Update the token state

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      mode: 'no-cors',
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    return response.json();
  };

  const clickEventHandlerWeather = async () => {
    try {
      const jsonData = await fetchData('https://localhost:7160/WeatherForecast');
      setData(jsonData);
    } catch (error) {
      console.error('Failed to fetch weather data:', error);
    }
  };

  const clickEventHandlerLogin = async () => {
    try {
      await fetchData('https://localhost:7160/Login');
      // For login, assuming you might not want to set any specific data
    } catch (error) {
      console.error('Failed to login:', error);
    }
  };

  return (
    <div className="row">
      <div className='col-md-6'>
        <ButtonComponent cssClass='e-danger' onClick={clickEventHandlerLogin}>Login</ButtonComponent>
      </div>
      <br></br><br></br>
      <div className='col-md-6'>
        <ButtonComponent cssClass='e-danger' onClick={clickEventHandlerWeather}>Weather</ButtonComponent>
      </div>
      {/* Display token. Ensure you handle displaying sensitive information securely */}
      <div style={{ width: '200px' }}>{token}</div>
      <br></br>
      <div style={{ width: '200px' }}>clerkOther: {token}</div>
    </div>
  );
};

export default Index;

Note: Another issue is CORS. I know I don’t need to do this, but that was causing other errors too. So I plan to research that once I’m about to hit the WEB API.

Discord Bot – DirectMessage Command

I’m coding a discord bot in JavaScript.
I try to make commandss that work in Direct Message but when I execute commands in Direct Message, the bot does not respond (as if it does not detect messages sent in DM). Which blocks the progress of the script.

I set the intents when the bot starts.

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.DirectMessages
    ]
});

I tried the “if (message.channel.type === ‘DM’)”

client.on('messageCreate', async message => {
    if (message.channel.type === 'DM' && message.content === '-hi') {
        try {
            await message.channel.send(':white_check_mark: | You have enabled the `-hi` command in server mode.');
        } catch (error) {
            console.error('error :', error);
        }
    }
});

I also tried “if (!message.guild)”

client.on('messageCreate', async message => {
    if (!message.guild && message.content === '-hi') {
        try {
            const user = message.author;
            await user.send(':white_check_mark: | You have enabled the `-hi` command in server mode.');
        } catch (error) {
            console.error('error :', error);
        }
    }
});

How to implement unique codes/ids to allow for remote participants?

I am currently working on a website that researchers at universities can use to set up and run participant-based studies. The current MVP is out, however I have noticed a big flaw in how the website is set up, and I am unsure how to solve it to fit my users’ needs.

Currently the website is set up as follows:

  1. Someone who wants to do a research study can make an account and setup a study. Their study’s information is stored in the MySQL database tied to their research project id and that project id is associated with their account id.

  2. When the researcher is ready to do their study, they can sign into the website (this grabs their study information) and go to the “start splash screen” which is meant for participants. Then, they can bring in participants into their lab/classroom/etc. and sit them down at the computer. The participant goes through the study that the researcher sets up.

  3. When they are done and click submit, the participant’s information is stored on the database yet again tied to the research project id. The backend knows what the research project id is because the browser is logged in to the researcher’s account.

This method works great for those doing in-person, in-lab studies where they can control the laptop the participant uses, etc. However, I’ve gotten feedback about how researchers want to be able to send out links to participants so that they can complete the study on their own. Due to the way the backend is set up, I am not sure how to modify the website to allow this.

Ideally, I would have a separate webpage for participants to be directed to and they would put in some sort of unique ID/code that would link them to the correct study. That special code would have to pull the correct study information from the database for the participant to see, and then submit the participant’s answers to the database under the correct research project.

My question is how would you go about this change? How would you generate unique ids that would allow specific study information to be pulled from the database while also keeping in mind security? I think it would be best to have a one-time use code so random people cannot get ahold of a code and use it multiple times.

I might also be thinking of this completely wrong. Any advice, technologies, or solutions you may have would be amazing. Please let me know if I need to provide any more context! Thank you!

P.S I am using vanilla HTML, CSS, JS (Knockout) for frontend. Node/Express js, MySQL for backend.

Errors in Setting JavaScript Cookies

I am placing a cookie to stop showing an offensive jokes warning alert if someone has already seen it but Adobe Brackets is showing 51 problems and 1 error and my JavaScript is not up to scratch. Don’t worry the cookie will not be used in identifying users and I have a cookie policy showing.

code below is there any way I can clear the error and problems. I have placed 100% of the code and the errors Brackets had identified following this.

Error is ESLint terminated with error:timeout

function writeCookie(name, value, hours) 
{}
function readCookie(name)
{}
function alert1()
{}

function writeCookie(name, value, hours)
{
    var expire = ""; 
    if(hours != null)
    {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}

function readCookie(name)
{
    var cookieValue,offset = "";
    var search = name + "=";
    if(document.cookie.length > 0)
    { 
        offset = document.cookie.indexOf(search);
        if (offset != -1)
        {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}

function alert1()
{
    var seen = readCookie("viewed"); 
    if(seen !== "yes") 
    { 
        if(confirm("***WARNING*** n Some of these jokes MAY be offensive. n  n If you do not wish to be offended n Please Press Cancel to return n Please note this will place a cookie on your computer"))
        {
            writeCookie("viewed", "yes", 9999); 
        }
        else 
        {
            window.location="index.htm" 
        }
    }
}

Problems as per brackets

1
Unexpected ‘(space)’. function writeCookie(name, value, hours)
2
Expected exactly one space between ‘)’ and ‘{‘. {}
2
Expected ‘{‘ at column 5, not column 1. {}
2
Missing ‘use strict’ statement. {}
4
Expected exactly one space between ‘)’ and ‘{‘. {}
4
Expected ‘{‘ at column 5, not column 1. {}
4
Missing ‘use strict’ statement. {}
6
Expected exactly one space between ‘)’ and ‘{‘. {}
6
Expected ‘{‘ at column 5, not column 1. {}
6
Missing ‘use strict’ statement. {}
9
Expected exactly one space between ‘)’ and ‘{‘. {
9
Expected ‘{‘ at column 5, not column 1. {
10
Missing ‘use strict’ statement. var expire = “”;
10
Expected ‘var’ at column 9, not column 5. var expire = “”;
10
Unexpected ‘(space)’. var expire = “”;
11
Expected ‘if’ at column 9, not column 5. if(hours != null)
11
Expected exactly one space between ‘if’ and ‘(‘. if(hours != null)
11
Expected ‘!==’ and instead saw ‘!=’. if(hours != null)
12
Expected exactly one space between ‘)’ and ‘{‘. {
12
Expected ‘{‘ at column 13, not column 5. {
13
Expected ‘expire’ at column 17, not column 9. expire = new Date((new Date()).getTime() + hours * 3600000);
14
Expected ‘expire’ at column 17, not column 9. expire = “; expires=” + expire.toGMTString();
15
Expected ‘}’ at column 13, not column 5. }
16
Expected ‘document’ at column 9, not column 5. document.cookie = name + “=” + escape(value) + expire;
16
‘escape’ was used before it was defined. document.cookie = name + “=” + escape(value) + expire;
17
Expected ‘}’ at column 5, not column 1. }
20
Expected exactly one space between ‘)’ and ‘{‘. {
20
Expected ‘{‘ at column 5, not column 1. {
21
Missing ‘use strict’ statement. var cookieValue,offset = “”;
21
Expected ‘var’ at column 9, not column 5. var cookieValue,offset = “”;
21
Missing space between ‘,’ and ‘offset’. var cookieValue,offset = “”;
21
Missing space between ‘,’ and ‘offset’. var cookieValue,offset = “”;
22
Expected ‘var’ at column 9, not column 5. var search = name + “=”;
22
Combine this with the previous ‘var’ statement. var search = name + “=”;
23
Expected ‘if’ at column 9, not column 5. if(document.cookie.length > 0)
23
Expected exactly one space between ‘if’ and ‘(‘. if(document.cookie.length > 0)
24
Expected exactly one space between ‘)’ and ‘{‘. {
24
Expected ‘{‘ at column 13, not column 5. {
24
Unexpected ‘(space)’. {
25
Expected ‘offset’ at column 17, not column 9. offset = document.cookie.indexOf(search);
26
Expected ‘if’ at column 17, not column 9. if (offset != -1)
26
Expected ‘!==’ and instead saw ‘!=’. if (offset != -1)
27
Expected exactly one space between ‘)’ and ‘{‘. {
27
Expected ‘{‘ at column 21, not column 9. {
28
Expected ‘offset’ at column 25, not column 13. offset += search.length;
29
Expected ‘end’ at column 25, not column 13. end = document.cookie.indexOf(“;”, offset);
29
‘end’ was used before it was defined. end = document.cookie.indexOf(“;”, offset);
30
Expected ‘if’ at column 25, not column 13. if (end == -1) end = document.cookie.length;
30
Expected ‘===’ and instead saw ‘==’. if (end == -1) end = document.cookie.length;
30
Expected ‘{‘ and instead saw ‘end’. if (end == -1) end = document.cookie.length;
30
Too many errors. (57% scanned). if (end == -1) end = document.cookie.length;