why read file in nodejs with promise.all is not effective?

my node version: v18.6.0

const fs = require('fs/promises');

async function readFileAsync(){
    try{
        return await fs.readFile('data.csv', {encoding: 'utf8'})
    }catch(err){
        throw err;
    }
}

async function main(){
    console.time('promise')
    await readFileAsync()
    await readFileAsync()
    await readFileAsync()
    await readFileAsync()
    await readFileAsync()
    console.timeEnd('promise')
}

async function main2(){
    console.time('promise.all')
    await Promise.all([readFileAsync(),readFileAsync(),readFileAsync(),readFileAsync(),readFileAsync()])
    console.timeEnd('promise.all')
}

// main()
main2()

There is no time difference between the main(188.444ms) and main2(202.826ms) functions.

there is event loop in nodejs, when request readFileAsync in Promise.all, this should be run parallel.

but run sychronize and run parellel, there is no time difference..

why this happend?

i expect use promise all is more effective. because, parellel

Why I can’t import googleapis inside e2e.js file inside Cypress

I am trying so send a video after each run in Cypress. I’m need to send the video of the spec run to google drive and get the weblink back. I’m using the googleapis package to send it. So, in the Before Hook inside the file e2e.js. When I put this line:

const { google } = require("googleapis");

And I’m getting the error:

  1) An uncaught error was detected outside of a test:
     TypeError: The following error originated from your test code, not from Cypress.

  > Cannot destructure property 'HTTP2_HEADER_CONTENT_ENCODING' of 'http2.constants' as it is undefined.

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
      at Object.eval (webpack:///./node_modules/googleapis-common/build/src/http2.js:25:7)
      at ./node_modules/googleapis-common/build/src/http2.js (http://localhost:61374/__cypress/tests?p=cypresssupporte2e.js:62097:30)
      at __webpack_require__ (webpack:///webpack/bootstrap:19:0)
      at Object.eval (webpack:///./node_modules/googleapis-common/build/src/apirequest.js:23:11)
      at ./node_modules/googleapis-common/build/src/apirequest.js (http://localhost:61374/__cypress/tests?p=cypresssupporte2e.js:61490:30)
      at __webpack_require__ (webpack:///webpack/bootstrap:19:0)
      at ./node_modules/googleapis-common/build/src/index.js (webpack:///./node_modules/googleapis-common/build/src/index.js:32:19)
      at __webpack_require__ (webpack:///webpack/bootstrap:19:0)
      at ./node_modules/googleapis/build/src/apis/abusiveexperiencereport/index.js (webpack:///./node_modules/googleapis/build/src/apis/abusiveexperiencereport/index.js:17:28)
      at __webpack_require__ (webpack:///webpack/bootstrap:19:0)

Does anyone have any solution or alternative so that I can send the video of the execution of each test to google drive

DOM Operation Unsuccessful – Show HTML in Element

Working code here is mixed with non working code. The code works up until the line where it commands the innerText to be of

x.innerHTML.substring(3,-3)

This is the function I am calling on a click EventListener for “click”. It does go to the function, I do get the console.log appearance. I do not get the change in text from empty to String and nor does it show up in the coder_grove portion of the code.

function makeOverSetup(ev)
{
        document.getElementById("styleVals").value = ev.target.getAttribute("style")
        document.getElementById("thisClasses").value = ev.target.getAttribute("class")
        document.getElementById("thisId").value = ev.target.getAttribute("id")
        document.getElementById("tagName").value = ev.target.tagName
        x = document.createElement("div");
        text = document.createTextNode(ev.target.outerHTML);
        x.appendChild(text);
        x.style.backgroundColor = "blue"
        console.log(x.innerHTML);
        if (document.getElementById("coded_grove").childElementCount.length == 0)
                document.getElementById("coded_grove").appendChild(x.firstChild);
        document.getElementById("coded_grove").firstChild.innerText = (x.innerHTML.substring(3,-3))
        elemCurrentNode = ev.target
        clicked = true
}

This is the site. Thank you in the future.

How to render Objects in a row React

This is the current response I am getting from the API I am working with:

"data": {
    "Login1": {
      "Public": [
        1,
        0
      ],
      "Team Only": [
        1,
        1
      ],
      "All": [
        1,
        1
      ]
    },

With this response, I want to render it in a table on the front-end like this

enter image description here

But the issue I am encountering is that both the values are clumping up together. I think the issue has to be in the way I am cycling through the code.

    const TableRows = (rows) => {
        const coeObject = Object.entries(rows);
        const row = coeObject.map((owner, mainIndex)=> {
          return (
            <TableRow key={console.log(`row-record-${owner}`)} highlightOnHover={true}>
              {Object.values(owner).map((value, index) => (
                <TableCell
                  key={`column-value-${index}`}
                  alignmentHorizontal={
                    tabsAlignment[props.metricComponent] &&
                    props.componentName != "Open_COE_Default"
                      ? tabsAlignment[props.metricComponent][index]
                      : index != 0
                        ? "center"
                        : ""
                  }
                >
                {loadData(value[props.selectedCategory], index, owner, mainIndex)}
                </TableCell>
              ))}
            </TableRow>
          );
        });
        return row;
      };

props.selectedCategory represent the Public, Team Only and All keys so when they are clicked the numbers cycle through.

My assumption is that I am not using Object.entries and Object.values properly.

wp.blocks.blockRegisterType Showing Error in Console – Gutenberg WordPress

I am not able to register a gutenberg block for a wordpress site, when I saw console it’s showing an error

‘Uncaught TypeError: wp.blocks.blockRegisterType is not a function at custom-cta-script.js?ver=1:1:11’

can someone help to fix it?

PHP code to enqueue js file:

function include_cta_js()
{
    wp_enqueue_script('custom-cta-script', plugin_dir_url(__FILE__) . 'custom-cta-script.js', array(
        'wp-blocks', 'wp-editor'
    ), true, false);
}
add_action('enqueue_block_editor_assets', 'include_cta_js');

JS File:

wp.blocks.blockRegisterType('custom-cta-script/custom-block', {
    title: 'CTA',
    icon: 'smiley',
    category: 'text',
    attributes: {
        text: { type: 'string' },
        url: { type: 'string' },
        backgroundColor: { type: 'string' },
        textColor: { type: 'string' }
    },
    edit: function (props) {
        return React.createElement("div", null, /*#__PURE__*/React.createElement("label", null, "Button Text"), /*#__PURE__*/React.createElement("input", {
            type: "text",
            value: "",
            placeholder: "Button Text"
        }), /*#__PURE__*/React.createElement("label", null, "Button URL"), /*#__PURE__*/React.createElement("input", {
            type: "text",
            value: "",
            placeholder: "Button URL"
        }), /*#__PURE__*/React.createElement("label", null, "Button Background Color"), /*#__PURE__*/React.createElement("input", {
            type: "text",
            value: "",
            placeholder: "Button Background Color"
        }), /*#__PURE__*/React.createElement("label", null, "Button Text Color"), /*#__PURE__*/React.createElement("input", {
            type: "text",
            value: "",
            placeholder: "Button Text Color"
        }));
    },
    save: function (props) {
        return null;
    }

});

JavaScript Fetch return NULL

I’m testing some things here, I have a very basic frontend with HTML where I send some data to the backend, I’m using the javascript fetch, I send a request and when I save it in the database the value is appearing as NULL , why?

I have the following code.

<!DOCTYPE html>
<body>
 <button onclick="test()">To Send</button>
<body>

<script>
function test(){
    const data = { name: "Anderson" };
    
    fetch('http://localhost:8081/user', {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json'
        }
    }).then(res => res.json())
      .then(data => console.log(data))
      .catch(error => console.log(error))
}
<script>

Converting CSV files Into JSON while Changing the Key Names in Javascript?

I have 2 CSV files and I want to grab specific data (while ignoring some columns) from the CSVs and turn them into a JSON format with nested arrays and specific key names. I also want to order the JSON by a specific value (orderID).

Here’s an example:

CSV file 1:

[ORDERIDENTIFIER, ORDERDTE, STORESTE, STOREADDRESS, STOREZIP, PRODUCTTYPE]

CSV File 2:

[ORDERTYPE, CUSTOMERAGE, CITY]

JSON:

[
    {
        "storeOrders": {
            "orderType": "2",
            "orderID": "22222",
            "orderDetails": {
                "productType": "Standard"
            },
            "collectedOrders": [
                {
                    "orderDate": "2023-09-03",
                    "customerAge": "22"
                }
            ],
            "storeDetails": {
                "storeState": "IA"
            }
        }
    },
    {
        "storeOrders": {
            "orderType": "1",
            "orderID": "444",
            "orderDetails": {
                "productType": "Standard"
            },
            "collectedOrders": [
                {
                    "orderDate": "2023-06-03",
                    "customerAge": "60"
                }
            ],
            "storeDetails": {
                "storeState": "RI"
            }
        }
    }
]

I have tried using the csvtojson but am unsure how to use it for multiple files/changing key names`

How to increase length of body Matter.js?

I want to increase the length of a rectangle body in matter.js making it longer. However using the scale() method can only change it on a y and x axis scale. This is a problem when My rectangle is rotated and its length will will changing constantly. How can I go about doing this in matter.js and p5.js?

“Cannot set properties of null” error in project

I’m a newbie with js/html, was nearing the completion of this small project when this error showed up after i added the “document.getElementById” tags.

This is the image which shows the error in the console

and the following is the function that im writing and the object that it is referring.

for(const key1 in reservedSeats){
    if(reservedSeats.hasOwnProperty(key1)){

        const obj=reservedSeats[key1];
        console.log(obj.seat)//checking to see if it returns the seat number
    
        document.getElementById(obj.seat).className="r";
        document.getElementById(obj.seat).innerHTML='R';
    }
}
var reservedSeats = {
    record1: {
        seat: "b19",
        owner: {
            fname: "Joe",
            lname: "Smith"
        }
    },
    record2: {
        seat: "b20",
        owner: {
            fname: "Joe",
            lname: "Smith"
        }
    },
    record3: {
        seat: "b21",
        owner: {
            fname: "Joe",
            lname: "Smith"
        }
    },
    record4: {
        seat: "b22",
        owner: {
            fname: "Joe",
            lname: "Smith"
        }
    }
};

saw multiple stackof saying that the object needs to be above the “getelementbyid” tag, have done that and it still doesn’t work.

Dropdown menu dynamic to each other

i just want to ask what went wrong with my codes? i have three dropdown selections, now what I want to happen is that if I select a name on selection 1, it will not show on selection 2 and selection 3. i want to it to be as flexible as it can be however i cant find a way to make it happen. badly need your help guys thank you guys

here’s my code

this is my table

    ` <table class="table table-striped table-bordered">
     <thead>
      <tr>
    <th>Gangway</th>
       <th>Time</th>
      <th>Name</th>
          
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>First Relieve</td>
          <td>0800H-1200H || 2000H-0000H</td>
          <td><div class="form-group">
          <select class="form-control" id="exampleFormControlSelect1">
          ';
              
                  // retrieve the list of names from the Personnel Status table
                  $names = array('Tony Parker', 'John Travolta', 'Bigboy Oneil');
                  echo '<option> </option>';
                  // generate the dropdown menu
                  foreach ($names as $name) {
                      
                      echo '<option href="#">' . $name . '</option>';
                  }
               echo '
          </select>
      </div></td>
        
        </tr>
        <tr>
          <td>Second Relieve</td>
          <td>1200H-1600H || 0000H-0400H</td>
          <td><div class="form-group">
          <select class="form-control" id="exampleFormControlSelect1">
          ';
              
                  // retrieve the list of names from the Personnel Status table
                  $names = array('Tony Parker', 'John Travolta', 'Bigboy Oneil');
                  echo '<option> </option>';
                  // generate the dropdown menu
                  foreach ($names as $name) {
                      
                      echo '<option href="#">' . $name . '</option>';
                  }
               echo '
          </select>
      </div></td>
          
        </tr>
        <tr>
          <td>Third Relieve</td>
          <td>1600H-2000H || 0400H-0800H</td>
          <td><div class="form-group">
          <select class="form-control" id="exampleFormControlSelect1">
          ';
              
                  // retrieve the list of names from the Personnel Status table
                  $names = array('Tony Parker', 'John Travolta', 'Bigboy Oneil');
                  echo '<option> </option>';
                  // generate the dropdown menu
                  foreach ($names as $name) {
                      
                      echo '<option href="#">' . $name . '</option>';
                  }
               
          </select>
      </div></td>
          
        </tr>
      </tbody>
    </table>
  ';`

//and this is my javascript associated with it

`
// get all the dropdown menus
var selects = document.querySelectorAll(“.form-control”);

// add an event listener to each dropdown
selects.forEach(function(select) {
    
    select.addEventListener("change", function() {
        
        // get the selected option
        var selectedOption = this.value;
        
        // loop through all the dropdowns
        selects.forEach(function(otherSelect) {
            
            // skip the current dropdown
            if (otherSelect === select) {
                return;
            }
            
            // loop through all the options in the other dropdown
            var options = otherSelect.querySelectorAll("option");
            options.forEach(function(option) {
                
                // hide the selected option in the other dropdowns
                if (option.value === selectedOption) {
                    option.style.display = "none";
                } else {
                    option.style.display = "";
                }
                
            });
        });
    });
});

`

I rewrote my code using fetch, and its not working

  • I rewrote my code using fetch instead of using callbacks, now the page is letting me loop through the api data. Even though I can see the data being fetched from the api in the console, when I use console.log*.

the rewrote code using fetch , not working

const generateHTML = (data)=>{
    let col = document.createElement("div");
        col.setAttribute("class", "col-6 py-2");
    cardContainer.appendChild(col);
    col.innerHTML = `
        <div class="col-6 py-2" > 
            <div class="card">
                <img src="${data.imageUrl}" class="card-img-top" title="${data.newsSite}">
                <div class="card-body">
                    <p class="card-title text-center fs-6"><strong><u>${data.title}</u></strong></p>
                    <p class="card-text fs-5 lead">${data.summary}</p>
                    <p class="source">Source | ${data.newsSite}</p>
                    <a href="${data.url}" target="_blank" class="btn btn-primary">${data.newsSite}</a>
                </div>
            </div>
        </div>
        `;
};

runCode.addEventListener("click", ()=>{
    
    fetch(theUrl).then((response)=>{
               let data = response.json()
               for(let i=0;i<data.length; i++){
                generateHTML(data[i]);
            }//
    });

});