How to store images in database?

I’m working on a platform using HTML, Javascript, SQL, Ajax and PHP.
The platform asks for a pictures and those pictures will have to be displayed later.
I’ve seen people saying that you shouldn’t store them in a database if they’re a lot, but just storing the path doesn’t seem like it would work because that would mean that the user could never change the pictures to another folder or delete them, right? And that wouldn’t work for what I want.
Does anyone have any suggestions on what I should do?

Javascript Array Foreach Callback Function With Recursion Push Values

I’ve been following this awesome solution. However for some reason on this block of code:

nodes.forEach(function(e){
    if(e.parent === currentNodeId){
        e = addChildrenToNode(e);
        node.children.push(e);
    }
});

The forEach callback function “e” param results to null instead of pushing the whole object into the node.children array. In order for me to get the actual values, I’ve manually set the values instead of using the “e” which will be the whole object e.g.:

node.children.push({ _id: e._id, name: e.name });

However, I’m not able to convert this line:

e = addChildrenToNode(e);

To do the recursion and append the children. I’m thinking that this is due to the old version of JS that we’re using on the server without the ES6 functionalities? Need your inputs. Thank you very much!

MongoDB TTL index never deletes records

I created an index as shown below and added a createdAt field to each new record added to the db. The records should be auto-deleted after 24 hours however I have waited days and nothing has been deleted.

db_connect.collection("records").createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

Adding record to the database

// Add info to db to search
    console.log("Adding info to database..");
    const otherAddress = e.target.address.value;
    const newRecord = {
        holderAddress: this.props.account,
        otherAddress: otherAddress,
        date: new Date(),
        data: encryptedData
    }
    await fetch("http://localhost:420/record/add", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(newRecord),
    }).catch(error => {
        window.alert(error);
    });

Endpoint it calls:

recordRoutes.route("/record/add").post(function (req, response) {
let db_connect = dbo.getDb();
let myobj = {
    holderAddress: req.body.holderAddress,
    otherAddress: req.body.otherAddress,
    data: req.body.data,
    createdAt: req.body.date
};
db_connect.collection("records").insertOne(myobj, function (err, res) {
    if (err) throw err;
    response.json(res);
});

Below is a screenshot from MongoDB website confirming there is an index..

enter image description here

Any help is greatly appreciated!

Javascript for loading a large number of facebook activity log comments rather than manually scrolling?

A script for deleting a number comments at once from facebook posts has worked as follows:

  • fb.com > Account > Settings & privacy > Activty log > Comments
  • Function F12 > Console
  • Copy and paste to the console:

.

setInterval(() => {
    for (const Button of document.querySelectorAll('div[aria-label="Action options"]')) {
        Button.click();
        document.querySelector('div[role="menuitem"]').click()
    }
}, 1000)

It processes (deletes) the comments that have been loaded on the screen. By scrolling down, the page loads and displays more comments. Without having to manually do this scrolling to load more, is there a away to load many screens worth?

How do I pass a .js variable to HTML input

I have been looking for a way to pass a js function to a HTML input. Is there any easy way to do that or my approach is wrong?

    <script>
            const input = window.location.search
            const clientID = input.split('?clientID=').pop()
   </script>

    <form action="" method="POST">
        <input type="submit">
    </form>

Opening a json file with javascript

I am trying to open a json file in javascript,

function test() {
  
    const jsonData= require('logins.json'); 

    alert(jsonData)
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <script defer src="test.js"></script>
</head>

<body>
  
</body>
    <button onclick="test()">test</button>
</html>

this is not working and logins.json is a thing, this is what is in it:


{

"Students":[
    {
        "username":"test",
        "password":"testi"    }
  ]
 }

any help is great, do I need to use Ajax or is it a silly mistake? I am new to javascript.

webpack asset resource not included for each import

in the context of aws lambda functions i currenlty need to access certain files in their runtime, for this i included this function below which will put a file that i import into the same folder importing the file.

const resolveWsdlInCurrentRuntime: Configuration['output']['assetModuleFilename'] = (pathData) => {
    return join(dirname(pathData.runtime.toString()), '[path]', '[base]');
}

// ... Webpack config ...
  module: {
    rules: [
      { test: /.ts$/, loader: 'ts-loader', options: {transpileOnly: true} },
      {
        test: /.(wsdl|xml)$/,
        type: 'asset/resource',
        generator: {
          filename: resolveWsdlInCurrentRuntime,
        },
      }
    ],
  },
  resolve: {
    extensions: ['.js', '.ts'],
    alias: {
      wsdl: resolve(__dirname, 'wsdl'),
    },
  },
// ...

so when import like below it automaticaly puts the file in the same folder and i can access it

import 'wsdl/some.wsdl'

the problem i encounter now however is that when i do the import import 'wsdl/some.wsdl' in two separate files the file will only be included in one of their outputs. Instead i would like for the file to be included each time i import it in a specific runtime.

does anyone have any idea how i can achieve this?

Is there a way to disable color mixing/overlapping in html canvas

I have a canvas and when i draw 2 things overlapping with low opacity, the opacity gets higher in the part where they are overlapping. Is there a way to make it all the same opacity even if 2 things are overlapping.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

ctx.fillStyle = "rgba(0, 0, 255, 0.2)";

ctx.fillRect(10, 10, 50, 50);
ctx.fillRect(20, 20, 50, 60);
ctx.fillRect(40, 5, 50, 40)
canvas {
  width: 100vw;
  height: 100vh;
}
<p>all of it should be the same color but the overlapping parts are darker</p>
<canvas id="canvas"></canvas>

How to persist resultset in Snowflake Stored Procedure written in Javascript?

I have a stored procedure that runs a sql command then it is run multiple times to call it multiple times. Is there a way to persist the resultSet so as not to run the snowflake query multiple times?

Currently

var my_sql_query = ` select * from table`;
var results = snowflake.execute({sqlText: my_sql_query});


while (results.next())
{
     script += results.getColumnValue(1);
}

... other script additions ...

// Second Run of the same script
var results = snowflake.execute({sqlText: my_sql_query});
while (results.next())
{
     script += results.getColumnValue(1);
}

Desired Output (as best as I can describe)

var my_sql_query = ` select * from table`;
var results = snowflake.execute({sqlText: my_sql_query});


while (results.next())
{
     script += results.getColumnValue(1);
}


// Second Run of the same script
while (results.next())
{
     script += results.getColumnValue(1);
}

How to speed up clock of browser

I want to speed up time in the browser without interfering local clock.

I’ve found an userscript that does exactly this (https://github.com/canguser/hooker-js/blob/master/src/plugins/timer-hooker/timeHooker.js)
But, I’m having trouble understanding it (I have a moderate understanding of js).

It’d be nice if anyone could explain the specific code responsible for speeding up the browser clock (The user script is large and most of it responsible for UI, which I’m not interested in).

I’d appreciate code snippets to run on the browser console to test the effects.

Test site: https://www.timeanddate.com/timer/

Chart.JS Display 5 largest values in the legend

I was wondering how to go about using Chart.JS to limit the amount of items displayed in the legend. I’d like to set essentially a max amount of 5, and it’ll display the 5 largest values in the legend. I’m assuming this would be done with a filter function in the options.plugins.labels, but I’m not sure how to go about checking the datasets against each other and then only displaying the 5 largest.

Thanks so much for the help

Remove all the white space between letters in a string but ignore space tab or enter at the end

I have searched and found ways to check for ALL whitespace existence between letters in a string but what about if the string contains a space, tab or enter at the end?

For example:

let str="John ";
console.log(str.includes(' '));

The above console.log will return true because there is a space at the end, however that is not relevant for me. I only wanted to check for:

let str="J o h n";

How to achieve this with Javascript ( and ignore space check at the end)?

response.json() throws “TypeError: Failed to fetch”

I use fetch for getting some resources from the server. I can see from logs that from time to time conversion to JSON fails on "TypeError: Failed to fetch" which is very interesting because should only happen when the request fails.

The simplified code I use:

const response = await fetch('https:/something.com/api')
await response.json() // -> throws TypeError: Failed to fetch

I cannot really find the case when it might happen. I tested possible cases and all failed on the first line of code, i.e. fetch('https:/something.com/api'). I have no idea when this might happen. I also should mention that it happens in modern browsers like chrome 99. So it is not definitely something like internet explorer thing.

Cases tested:

  1. Network error – user disconnected from the internet
  2. CORS – missing CORS headers

Unable to debug Opensource repos download from githup such as ramda or lodash

Unable to debug Opensource repos download from githup such as ramda or lodash.

Using those libraries are easy but cannot find a way to debug/edit it even if its adding console.log(“hello”) into a simple add function.

If I run add.js in either ramda or lodash I get a similar error.

”’
Uncaught SyntaxError c:Usersaspiesourcereposlodashadd.js:1
import createMathOperation from ‘./.internal/createMathOperation.js’
^^^^^^

SyntaxError: Cannot use import statement outside a module
at compileFunction (node:vm:352:18)
”’

Using multiple modals linked to th:href

I am trying to generate modals from hrefs:

<ul class="unordered-list" th:each="barOrder : ${OrdersByUser}">
                <li>
                    <a th:href="@{/users/details/{userId}/orderHistory/{orderId}(orderId=${barOrder.orderId}, userId=${billyUserId})}">
                        <div class="grid-orderHistory-parent">
                            <div class="grid-user-child-left"  th:text="${#temporals.format(barOrder.getDateTime(), 'dd-MM-yyyy HH:mm')}"></div>
                            <div class="grid-user-child-left"  th:text="${barOrder.getTotalPriceDisplayString(barOrder.getTotalPrice())}"></div>
                            <div class="grid-user-child-left" th:text="${barOrder.getBartenderName()}"></div>
                        </div>
                    </a>
                </li>
            </ul>

It is for an overview with orderhistory. For every order I want to details to pop up in a modal. So far I tried using JS but with no luck.

TIA