Didn’t get response from the query when creating DB Pool. Nodejs Mysql

Earlier I am working with the single connection but now I am trying to create a DB Pool in Nodejs using Mysql.

I am following the Single Pattern or Class-Based Pattern to create a query and other operations

Earlier Configuration (Everything working fine)

const connection = mysql.createConnection({
  host: dbConfig.HOST,
  user: dbConfig.USER,
  password: dbConfig.PASSWORD,
  database: dbConfig.DB
});

connection.connect();
connection.query("SET AUTOCOMMIT=false;", (err) => {
  if(err){
    console.log(err)
    console.log("Couldn't set auto commit to false")
  }else{
    console.log("AutoCommit set to false")
  }
});

function query(sql, params, autorollback) {
  return new Promise((resolve, reject) => {
    //let currentTime = new Date().valueOf();
    let query = connection.query(sql, params, (err, resp) => {
      if(err && autorollback) {
        return resolve(rollback(err));
      }
      else if (err) {
        console.log(err)
        return reject(err);
      }
      //console.log("Time Taken: ", new Date().valueOf() - currentTime, "n", query.sql);
      //console.log(resp);
      resolve(resp);
    });
  });
}

Create Pool Configuration (Didn’t get the response from the query)

const connection = mysql.createPool({
    host: dbConfig.HOST,
    user: dbConfig.USER,
    password: dbConfig.PASSWORD,
    database: dbConfig.DB,
    connectionLimit: 4,
});

connection.getConnection(function (err, conn) {
    conn.query("SET AUTOCOMMIT=false;", (err) => {
        if (err) {
            console.log(err)
            console.log("Couldn't set auto commit to false")
        } else {
            console.log("AutoCommit set to false")
        }
    });
});

function query(sql, params, autorollback) {
    console.log(sql)
    return new Promise((resolve, reject) => {
        //let currentTime = new Date().valueOf();
        connection.getConnection(function (err, conn) {

            if (err) {
                console.log(err)
                return reject(err);
            }
            let query = conn.query(sql, params, (err, resp) => {
                console.log(sql)
                if (err && autorollback) {
                    return resolve(rollback(err));
                }
                else if (err) {
                    console.log(err)
                    return reject(err);
                }
                //console.log("Time Taken: ", new Date().valueOf() - currentTime, "n", query.sql);
                //console.log(resp);

                resolve(resp);
                conn.release();
            });
        })
    });
}

when res.render() method used, internal express server response error with status code 500

I am new to node.js and please be patient with me.I am experiencing difficulties with internal express server.
My goal is to make Get request and load the data from external server and render it on my website.Although I successfully loaded the data from external server and parse it into javascript object. When I console log it, I can see javascript object is correctly transformed. But when I render it on my ejs file, It was said that the array I passed is undefined. I spelled correctly variables names. Then I inspect it by using developer tool and I got the message in console as below

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

let me show the code I used

const express = require(“express”);

const bodyParser = require(“body-parser”);

const app = express();

app.set(‘view engine’, ‘ejs’);

app.use(bodyParser.urlencoded({

extended: true

}));

app.use(express.static(__dirname + “/public”));

// const ejs = require(“ejs”);

const https = require(‘https’);

app.get(“/Health”,function(req, res){

let healthUrl = “https://newsapi.org/v2/top-headlines/?

category=health&apiKey=5ad38a0db6944d22aa81b5420f6a62f4&language=en”;

https.get(healthUrl, (resp) => {

let data ='';




resp.on("data",(chunk)=>{




  data += chunk;




});




resp.on("end",()=>{




let newData =  JSON.parse(data);

let allArticles = newData.articles;

});

}).on(‘error’, (e) => {

console.error(e);

});

res.render(“Health”,{allArticles:allArticles});

});

when I console log(allArticles); in app.js file, I can see the javascript that I loaded. But when I render it on ejs file, error occered and got the message that “allArticles is undefined”
I checked it in ejs file like below:

%-include(‘partials/header’)-%>

<% console.log(allArticles) %>

<%-include(‘partials/footer’)-%>

then I inspect it by dev tool , as I mensioned above, I got the message like this:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)

How to resize canvas with Animated Text on it?

Good evening everyone I am new to this site so forgive me for any mistake I have made.

I am practice on this project and I want to add one more letter at the end like ‘N’ or symbol like ‘!’. I cannot find the way to do this. I tried a lot of things like:

  • I change the width from css
  • I change the width from javascripts
  • I change and test a lot of things from javascript file and I did a lot of combinations between css file and javascript

But all of this is wrong. It spoils me and confuses my text in output. When I cahnge the width from css file it makes the canvas with the text bigger but not the size to add one more letter at the end.
What must i change to add one more digit at the end?
Thank you!

Html page not responding to first button click

I am trying to build my own css/javascript popup. The code works fine on the first button click and on the overlay click.

When I try to reload the popup I have to click the button twice for it to function, It seems like the javascript is not resetting the csv back to its original state.

html

    <div id="shade" class="shade" onclick="myFunction('mdiv',0,0)" ></div>
    <div id="mdiv" class="mdiv"><img src="./graphics/volunteer.webp" style="max-width:98%; width:98%;" /></div>
    <button onclick="myFunction('mdiv',300,350)" >Click me</button>

css

 .shade {
  background-color: rgba(0,0,0,0.3);
  bottom: 0;
  cursor: pointer;
  display: none;
  height: 100%;
  left: 0;
  opacity:0;
  position: fixed;
  right: 0;
  top: 0;
  transition: opacity 1s;
  width: 100%;
  z-index: 2;
  }
 .mdiv {
  background-color:white;
  border:4px solid blue;
  border-radius:12px;
  border-style:double;;
  box-shadow: 2px 1px 18px 10px rgba(255,255,255,0.75);
  display:none;
  height:0;
  left:50%;
  opacity:0;
  padding:15px;
  position:absolute;
  text-align:center;
  top:50%;
  transform: translate(-50%,-50%);
  transition: width 1s, height 1s, opacity 1s;
  width:0;
  z-index:10;
  }

javascript

     var vw = 0;
 var vh = 0;

 function myFunction(idx, vw, vh) {
    if (document.getElementById(idx).style.display === "none") {
        document.getElementById('shade').style.display = "block";
        setTimeout(function() {
            document.getElementById('shade').style.opacity = 1;
        }, 100);
        document.getElementById(idx).style.display = "block";
        setTimeout(function() {
            document.getElementById(idx).style.width = vw + 'px';
        }, 100);
        setTimeout(function() {
            document.getElementById(idx).style.height = vh + 'px';
        }, 100);
        setTimeout(function() {
            document.getElementById(idx).style.opacity = 1;
        }, 100);
    } else {
        setTimeout(function() {
            document.getElementById(idx).style.width = '0px';
        }, 100);
        setTimeout(function() {
            document.getElementById(idx).style.height = '0px';
        }, 100);
        setTimeout(function() {
            document.getElementById(idx).style.opacity = 0;
        }, 100);
        document.getElementById(idx).clientWidth = 0;
        if (document.getElementById(idx).style.opacity == 0) {
            document.getElementById(idx).style.display = "none";
        }
        setTimeout(function() {
            document.getElementById('shade').style.opacity = 0;
        }, 100);
        setTimeout(function() {
            document.getElementById('shade').style.display = "none";
        }, 600);
    }
 }

Could anyone help please?

How do I fix this Uncaught TypeError: Cannot set properties of null (setting ‘src’)?

I’m trying to change the image that is displayed on the modal, but I get this error message when I try to target the img src:

Uncaught TypeError: Cannot set properties of null (setting ‘src’) . How do I fix this?

What am I doing wrong? Here is my codepen:

https://codepen.io/Montpellier81/pen/zYpyoEQ?editors=1111

HTML

<div class="container">
</div>

<div class="modal">
  <div class="modal-content">
    <i class ="modal-close">X</i>
    <img id="modal-image" src="" alt="image">
    <div class ="modal-info">
    <h2 class="modal-name"></h2>
    <h3 class="modal-location"></h3>
   </div>
  </div>
</div>

CSS

.container {
    display: flex;
}
.card{
    width: 300px;
    height: 300px;
    padding: 20px 20px;
    cursor: pointer;
}
.modal {   
    position: fixed; 
    display: none;  
    z-index: 1; 
    left: 0; top: 0;
    height: 100%;
    width: 100%;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.6);
}
.modal-content{
    background-color: white;
    padding-top: 150px; 
    margin: auto;
    display: block;
    width: 60%;
    display: flex;
    position: relative;
}
#modal-image{
    width: 300px;
    height: 150px;
    border: 2px solid black;
    justify-content: center;
}
.modal-close{
    top: 15px;
    right: 20px;
    position: absolute;
    color: red;
    font-size: 30px;
    cursor: pointer;
}

and JavaScript

const modal = document.querySelector('.modal');
const close = document.querySelector('.modal-close');
const attractions = [
    {
        "img": "https://montpellier81.github.io/landmarks/eiffel.jpg",
        "name": "Eiffel Tower",
        "place": "Paris, France",
    },
    {
        "img": "https://montpellier81.github.io/landmarks/uluru.jpg",
        "name": "Uluru, Ayers Rock",
        "place": "Uluru-Kata Tjuta National Park, Australia",    
    },
    {
        "img": "https://montpellier81.github.io/landmarks/taj.jpg",
        "name": "Taj Mahal",
        "place": "Agra, India",
    }
  ]
  
     
let html = '';
    attractions.map((item, index) => {
        html += `
        <div id = '${index}' onclick = 'createModal(event)' class="card">
            <div class="card-image">
                <h2 class="name">${item.name}</h2>
                <h3 class="place">${item.place}</h3>
                <img id="image" src="${item.img}" alt="">
            </div>
        </div>
        `
    })
    document.querySelector('.container').innerHTML = html;

function createModal(event){
    let card = event.target.parentNode.parentNode
    let index = parseInt(card.id)
    let object = attractions[index]
    let name = object.name 
    document.querySelector('.modal-name').innerText = name;
    let locale = object.place
    document.querySelector('.modal-location').innerText = locale;

  let picture = object.img
   document.querySelector('.modal-image').src = picture;
    
        modal.style.display = "block";
        close.onclick = function(){
          modal.style.display = "none";
        };
    };


Loop until find an array empty in Javascript

I’m trying to find a solution to make a loop (Javascript) until the array of object is empty. Here the object that I want to use :

"chain": {
    "evolves_to": [{
        "evolves_to": [{
            "evolves_to": [],
            "species": {
                "name": "nidoqueen"
            }
        }],
        "species": {
            "name": "nidorina"
        }
    }],
    "species": {
        "name": "nidoran-f"
    }
}

I would like to loop until to find the variable evolves_to empty. and in each loop using the species.name, to list the evolution, in my case :
nidoran-f -> nidorina -> nidoqueen

I can not find yet a good way to do it. A bit lost. Thank you for your help 😉

print key as well as value in nested JSON [closed]

I want to print key as well as value,tried several approach with .map but did not get expected output

resData =[
  {
    _index: 'web',
    _type: 'event',
    _id: 'web+0+93',
    _score: null,
    _source: {
      'os-name': 'Windows',
      'browser-version': '90.0',
      'os-version': '10',

    },
    sort: [ '20210729T05:48:03Z' ]
  }
]

Expected Output

'os-name': 'Windows'
'os-version': '10'

Toggling individual elements of the same class in dropdown menu

I am building a dropdown menu. As is, when I open one submenu, it stays open, even if I open a second submenu. When I open the second submenu, it should close any other open menus.

const submenuLinks = document.querySelectorAll('.has-submenu > a');
submenuLinks.forEach(element => element.addEventListener('click', function(e) {
    var submenu = element.nextElementSibling;
    if (submenu.classList.contains('menu-hide')) { 
        submenu.classList.add('menu-show');
        submenu.classList.remove('menu-hide');
    } else {
        submenu.classList.add('menu-hide');
        submenu.classList.remove('menu-show');
    }
}));
.menu-hide {
    display: none;
}

.menu-show {
    display: block;
}
<nav>
    <ul class="menu">
        <li>
            <a href="#">Menu Item 1</a>
        </li>
        <li class="has-submenu">
            <a href="#">Menu Item 2 &raquo;</a>
            <ul class="menu-sub menu-hide">
                <li><a href="#">Submenu Item 1</a></li>
                <li><a href="#">Submenu Item 2</a></li>
                <li><a href="#">Submenu Item 3</a></li>
            </ul>
        </li>
        <li class="has-submenu">
            <a href="#">Menu Item 3 &raquo;</a>
            <ul class="menu-sub menu-hide">
                <li><a href="#">Submenu Item 1</a></li>
                <li><a href="#">Submenu Item 2</a></li>
                <li><a href="#">Submenu Item 3</a></li>
            </ul>
        </li>
    </ul>
</nav>

Run JS function and WASM module concurrently

I am trying to create some sort of a benchmark app that would concurrently run WASM module and its’ equivalent JS function and then compare execution time of those two. I have tried using promises, callbacks, and the example from MDN with using await Promise.all(arrayOfPromises), but in each case JS function starts running after the WASM module is done.

Code is down below, ignore the DOM boilerplate:

import { default as wasm } from "./pkg/hello_world.js"
import { sortRandomArray } from "./src/sorting.js"

window.onload = () => {
    const btn = document.getElementById("inputConfirmation");
    addListeners(Array(btn), runTestAndPrintResult);
}

async function runWasmModule(sortRandomArray, arraySize) {
    return new Promise(() => {
        const time = parseFloat(sortRandomArray(arraySize));
        console.log('wasm done ' + time);
    });
}

async function runJSAlgo(sortRandomArray, arraySize) {
    return new Promise(() => {
        const time = sortRandomArray(arraySize) / 1000;
        console.log('js done ' + time);
    });
}

function addListeners(elements, fun) {
    for (const element of elements) {
        element.addEventListener("click", fun);
    }

    document.addEventListener("keypress", event => {
        if (event.key === "Enter") {
            fun();
        }
    })
}

const runTestAndPrintResult = async () => {
    let arraySize = document.getElementById("arraySizeInput").value;
    if (arraySize === "") {
        return;
    }

    arraySize = parseInt(arraySize);
    const n = document.createElement("h1");

    if (arraySize <= 1) {
        n.textContent = "Nice try :)";
        document.body.appendChild(n);
        return;
    }

    const wasmInstance = wasm();
    wasmInstance.then(async (module) => {
        await Promise.all([
            runWasmModule(module.sort_random_array, arraySize),
            runJSAlgo(sortRandomArray, arraySize),
        ]);
    }).catch(err => {
        console.error(err);
    })
}

I do understand that JS is a single-threaded language but I got confused with all of the terms online about asynchronous nature. If there is no way to do this in JS, is there anything else I could try in order to realize this?

Type ‘number’ is not assignable to type ‘Element’

I am creating custom hook useArray in react with typescript which perform methods of array like push,update,remove etc. In js it is working fine but in ts there are some errors. below are the code from files:
useArray.ts

import { useState } from "react";
export default function useArray<T extends Element>(defaultValue: T[]): {
    array: T[],
    set: React.Dispatch<SetStateAction<T[]>>,
    push: (elemet: T) => void,
    remove: (index: T) => void,
    filter: (callback: (n: T) => boolean) => void,
    update: (index: number, newElement: T) => void,
    clear: () => void

} {
    const [array, setArray] = useState(defaultValue);

    function push(element: T) {
        setArray((a) => [...a, element]);
    }

    function filter(callback: (n: T) => boolean) {
        setArray((a) => a.filter(callback));
    }

    function update(index: number, newElement: T) {
        setArray((a) => [
            ...a.slice(0, index),
            newElement,
            ...a.slice(index + 1, a.length),
        ]);
    }

    function remove(index: number) {
        setArray((a) => [...a.slice(0, index), ...a.slice(index + 1, a.length)]);
    }

    function clear() {
        setArray([]);
    }

    return { array, set: setArray, push, filter, update, remove, clear };
}

ArrayComp.tsx :

import ArrayComp from "./components/ArrayComp";

function App() {
  return (
    <div className="App">
      <ArrayComp />
    </div>
  );
}

export default App;

I am getting this error: “Type ‘number’ is not assignable to type ‘Element'” at multiple places.I want that array elements can be of any possible type but i don’t want to make its type as any.any suggestions will be appreciated.

Use middlewares only for json server specific routes

How can I use a middleware for my json-server ONLY FOR specific routes? In the json-server docs, I can see the following instructions:

server.use(customMiddleware)
server.use(jsonServerRouter) // customMiddleware should be executed ONLY FOR jsonServerRouter

/*
Problem is here, customMiddleware has already been executed,
so following routes will use the middleware too
*/
server.use(otherRoutes)

How to split text into key-pair value in JavaScript?

I have received result from Raspberry Pi as Text format and I want to use these text to insert into MongoDB as key-pair value or JSON for my Node.js Application. However, I am quite new with JavaScript and trying to figure out the solution. Please help me if you have any suggestion, Thank you very much.

Example:

//Text from Raspberry Pi

1, 2300,450
2, 2200, 920
3, 3400, 440

and I want it to be

[
 {
  person: 1,
  x position: 2300,
  y position: 450
 }, 
 {
  person: 2,
  x position: 2200,
  y position: 920
 }, 
 {
  person: 3,
  x position: 3400,
  y position: 440
 }
] 

where to start and what to learn

hello im a beginner coder,currently i have an idea for my company (non coded related) where i can take pictures of aparament maps and store gate codes. What should i learn so i can make a website save images and be able to read the buildings numbers and generate a pathway to it or a simple star, that way i can locate a unit/aparement faster, also storing gate codes since our Work Orders dont always have gate codes, we either have to look for one or wait until someone lets us in. i know simple html and css, currently trying to understand javascript