How is it possible to use a single catch() at the end in a chain of promises?

I need please a detailed explanation of how it is possible to use a single catch() at the end of the promise chaining to catch any errors.

How is the reason for rejection “passed on” to the end of the chain?

I know that when a function is not passed to the 2nd argument of a then() it “passes the inconvenience”, but I don’t know if it is related to my question

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

onRejected Optional

A Function asynchronously called if the Promise is rejected. This
function has one parameter, the rejection reason. If it is not a
function, it is internally replaced with a thrower function ((x) => {
throw x; }) which throws the rejection reason it received.

Is it possible to run a single one function in Visual Studio Code’s terminal?

I’m new here as well as new in programming. I just wanted to ask a thing, that would help me a little with my very first JS online course, that I’m studying since a few days.

I wrote a very simple multiply function:

function multiply (x) {
    return x * 2;
}

If I link my js file with a html file and run the console in Dev Tools, I can just type in “multiply(2)” to get the answer “4” without any errors.

Is there any option, to run the function in Visual Studio Code’s terminal? So I don’t habe to link every single js file with a single, simple function with html file?

I’m using node. But when I type in “node nameofjsfile.js” to run the program, and then for example “multiply(2)”, the program doesn’t work and I get ObjectNowFound, CommandNotFoundException. If I write “node nameofjsfile.js multiply(2)”, I get “Syntax error, Code: 800A03EA”.

How do you build open source software with cloud architecture in mind?

My current project is an open-source and a monorepo project. However, I intend to offer a cloud platform for users who prefer not to self-host the product. In the cloud platform, I plan to include certain limitations and monthly subscriptions that will not be present in the self-hosted version. I am unsure of how to develop software with such distinct versions. Would the solution involve setting up environment variables or configurations, using git submodules, or something entirely different? Just to add one more thing, I wanted to use different authentication service on cloud platform than the self-hosted version.

Although I have researched open-source projects that provide cloud platforms, I have not yet found a definitive answer to my question.

How to display a confirm dialog when clicking an link?

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.

<a href="?status=1">My Link</a>

If the user clicks “Yes”, the link should load, if “No” nothing will happen.

What is the easiest way to do this?

There are several ways to do this, but I have forgotten the easiest way

HTML Table footer in @media print with different content on each page

Let’s say I have a table that represents a bill/invoice. It can span multiple pages, so on the last page I want to display total costs in the footer, but in the previous footers, I want to display the subtotal ones.

Is something like that possible to achieve without creating multiple tables? Creating multiple ones would have the downside of having to either calculate the table height dynamically or limit it to some pragmatic number of items per page so the table chunks never overflow from the page

Sending message through content script (1) -> background.js -> content script (2) cause Could not establish connection. Receiving end does not exist

I want to send message between two tabs with different urls. My general idea is using long-lived connections and passing message between two content scripts and one background.js:

On www.website1.com I inject content script (1) and run:

const port = chrome.runtime.connect({name: "my_chanel"});
port.postMessage({file: 'some static message'});

This message will be handled by background.js – there I’ll open new tab with `www.website2.org’ and forward obtained message:

chrome.runtime.onConnect.addListener(port => {
  if (port.name === "my_chanel") {
    port.onMessage.addListener(msg => {    // wait for message from content script (1)...
        if (msg?.file) {
            chrome.tabs.create({url:'www.website2.org'}, newTab => {    // if msg exist open new tab and forward msg
                const port = chrome.tabs.connect(newTab.id, {name: "my_chanel"});
                port.postMessage(msg);
            });
        } else {
            console.error('Service worker got empty message from 1st content script');
        }
    });
  }
});

Last, but not least – on `www.website2.org’ I’ll also run content script (2) which wait for message from background.js:

const port = chrome.runtime.connect({name: "my_chanel"});
port.onMessage.addListener(msg => {
    console.log(msg.file);
});

Everything works except content script (2) – line port.onMessage.addListener(...) thrown an error:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

There is already described a bunch of similar problems, but all of them about simple one-time request (not long-lived like in my scenario) and asynchrous calls (I’m sending static text and there is no async calls).

There is no more details, I’ve disabled other extensions as well, for making sure that there is no interferention.

Can anyone told me where I made a mistake?

how to fix this error in javaScript : Uncaught ReferenceError: require is not defined

i am making a login page to a system and i have the users of the system and their information in a json file:

{
        "id": 1,
        "first_name": "John",
        "last_name": "Doe",
        "email": "[email protected]",
        "password": "password123",
        "role": "organizer"
      },
      {
        "id": 2,
        "first_name": "Jane",
        "last_name": "Doe",
        "email": "[email protected]",
        "password": "password123",
        "role": "organizer"
      },
      {
        "id": 3,
        "first_name": "Bob",
        "last_name": "Smith",
        "email": "[email protected]",
        "password": "password123",
        "role": "reviewer"
      },

and i want to make sure that only these users are going to login to the system. I used const users = require(‘./users.json’); then iterate in the array and compare the input email and password but it doesn’t work.

i tried const users = require('./users.json'); but it says in the browser that require is not defined. i also tried to put the users in a normal array in javascript page itself and it worked, but I don’t want to do this, I want to iterate the users from the json file.

Undefined array key in php file, POST request from AJAX call in Jquery

I am working on a small project in which I have to fetch some weather information when a user clicks on a button.

For some reason my $_REQUEST array does not contain the desired key even though I seemed to have entered the right settings in my HTML form as well as in my JS.

I apologize if the mistake might seem silly but I am new to PHP hence why the confusion.

// PHP //

<?php

//var_dump($_REQUEST);
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$executionStartTime = microtime(true);

$url =
    'https://api.openweathermap.org/data/2.5/weather?lat=' .
    $_REQUEST['latitude'] .
    '&lon=' .
    $_REQUEST['longitude'] .
    '&appid=mykey';

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$data = curl_exec($ch);

curl_close($ch);
//$encode = json_encode($data);
$decode = json_decode($data, true);
//echo($_REQUEST);
header('Content-Type: application/json; charset=UTF-8');

?>


/// JS/JQUERY


        $.ajax({
            url: "../project1/php/weather.php",
            type: 'POST',
            dataType: 'json',
            data: {
                latitude: $('#latitude').val(),
                longitude: $('#longitude').val()
            },
            success: function (result) {

                console.log(JSON.stringify(result));

                if (result) {

                    // to be updated

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(errorThrown));
            }
        });


    }).addTo(map);



/// HTML//

.....

<body>
    <form method="POST">
        <input type="number" name="latitude" id="latitude" step="0.01"/>
        <input type="number" name="longitude" id="longitude" step="0.01"/>
        <input type="submit" value="submit">
    </form>
    <nav class="navbar">
        <img src="globeBig.png" class="logo"/>
        <h1>The Gazetteer</h1>
        <ul class="list">
            <li>Country Information</li>
            <li>Weather</li>
            <li>Earthquakes</li>
            <li>
                <select class="country"></select>
            </li>
        </ul>
    </nav>
    <div id="map"></div>

….

Accessing object properties inside template literal [duplicate]

Am trying to access properties within an object using dot notation in a template literal but am receiving an error [object object] here is my code

const Mark1 = {
  fullName: mark,
  mass: 7.8,
  height: 1.6,
  calcBMI1: function() {
    this.bmiMark = this.mass / this.height ** 2;
    return this.bmiMark;
  }
}

const markBmi = Mark1.calcBMI1();
console.log(markBmi);

const john1 = {
  fullName: john,
  mass: 92,
  height: 1.9,
  calcBMI1: function() {
    this.bmiJohn = this.mass / this.height ** 2;
    return this.bmiJohn;
  }
}

const johnBmi = john1.calcBMI1();
console.log(johnBmi);

if (markBmi > johnBmi) {
  console.log(`${Mark1.fullName}'s BMI ${markBmi} is higher than ${john1.fullName}'s BMI ${johnBmi} `);

} else if (johnBmi > markBmi) {
  console.log(`${john1.fullName} BMI ${johnBmi} is higher than ${Mark1.fullName} bmi ${markBmi}`);
}

i was expecting to get

John BMI 25 is higher than mark bmi 3.0 but am getting this [object Object] BMI 25.48476454293629 is higher than [object Object] bmi 3.0468749999999996

WordPress Gutenberg block with Border Box Control component not working

I’m trying to build a basic block example with the Border Box Control component:

import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, RichText, InspectorControls } from '@wordpress/block-editor';
import { __experimentalBorderBoxControl as BorderBoxControl, PanelBody, __experimentalToolsPanelItem as ToolsPanelItem } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';

registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {
    apiVersion: 2,
    title: 'Example: Editable (esnext)',
    icon: 'universal-access-alt',
    category: 'design',
    attributes: {
        content: {
            type: 'string',
            source: 'html',
            selector: 'p',
        },
    },
    example: {
        attributes: {
            content: 'Hello World',
        },
    },
    edit: ( props ) => {
        const {
            attributes: { content },
            setAttributes,
            className,
        } = props;
        const blockProps = useBlockProps();
        const onChangeContent = ( newContent ) => {
            setAttributes( { content: newContent } );
        };
        const colors = [
            { name: 'Blue 20', color: '#72aee6' },
            // ...
        ];
        const defaultBorder = {
            color: '#72aee6',
            style: 'dashed',
            width: '1px',
        };
        const [ borders, setBorders ] = useState( {
            top: defaultBorder,
            right: defaultBorder,
            bottom: defaultBorder,
            left: defaultBorder,
        } );
        const onChange = ( newBorders ) => setBorders( newBorders );

        return (
            <>
                <InspectorControls>
                    <PanelBody title={ __( 'Settings', 'example-03-editable-esnext' ) }>
                        <BorderBoxControl
                            colors={ colors }
                            label={ __( 'Borders' ) }
                            onChange={ onChange }
                            value={ borders }
                        />
                    </PanelBody>
                </InspectorControls>
                <div { ...blockProps }>
                    <RichText    
                        tagName="p"
                        onChange={ onChangeContent }
                        value={ content }
                        style={ {
                        ...( borders.top.color ? { borderTopColor: borders.top.color } : {} ),
                        ...( borders.top.style ? { borderTopStyle: borders.top.style } : {} ),
                        ...( borders.top.width ? { borderTopWidth: borders.top.width } : {} ),
                        ...( borders.right.color ? { borderRightColor: borders.right.color } : {} ),
                        ...( borders.right.style ? { borderRightStyle: borders.right.style } : {} ),
                        ...( borders.right.width ? { borderRightWidth: borders.right.width } : {} ),
                        ...( borders.bottom.color ? { borderBottomColor: borders.bottom.color } : {} ),
                        ...( borders.bottom.style ? { borderBottomStyle: borders.bottom.style } : {} ),
                        ...( borders.bottom.width ? { borderBottomWidth: borders.bottom.width } : {} ),
                        ...( borders.left.color ? { borderLeftColor: borders.left.color } : {} ),
                        ...( borders.left.style ? { borderLeftStyle: borders.left.style } : {} ),
                        ...( borders.left.width ? { borderLeftWidth: borders.left.width } : {} )
                        } }
                    />
                </div>
                
            </>
        );
    },
    save: ( props ) => {
        const blockProps = useBlockProps.save();
        return (
            <RichText.Content
                { ...blockProps }
                tagName="p"
                value={ props.attributes.content }
            />
        );
    },
} );

The component shows up in the Inspector wih default settings, but as soon as I change any of the settings, I get the following console error:

TypeError: Cannot read properties of undefined (reading 'color')

I can’t see my error but I’m new to react, so I feel like it is an error with that than the component itself.

Any ideas?

Unable to render React components inside App.jsx

I keep having a blank screen after succefully importing my components contained in the components folder in the App.jsx component.

import React from 'react'

import Header from './components/Header/header'
import Nav from './components/navigation/navigation'
import About from './components/about/about'
import Experience from './components/experience/experience'
import Services from './components/services/services'
import Testi from './components/testiomonials/testi'
import Contact from './components/contact/contact'
import Footer from './components/footer/footer'


const App = () => {
  return (
  <>
      <Header />
      <Nav /> 
      <About />
      <Experience />
      <Services />
      <Testi />
      <Contact />
      <Footer />
    </>

  )
 }

export default App`

Here is File structure

This is the Results

I have tried to take the App.jsx out of the src folder but it still doesnt work. what can i do

Replace sequence of characters without RegExp in JS

I am trying to replace a sequence of characters from string without regular expressions.

let text = "aaaaabbbbbccccccdfgabgaaa"

// expected output - "abcdfgabga"

All sequances must be replaced by the char only 1 time and if the same char is matched later it should stay in the result as well.

Any help without RegExp will be much appreciated.

I’ve tried with .replace and .substring but I am hitting a hard rock with both because when the chars at the end are matched it replaces the ones at the beginig.

socket io and nodejs for updating a table in react

hi i have node server and i want to pass data with socket io but it not wor this is my code :

const express = require(“express”);

const mongoose = require(“mongoose”);

const socketio = require(“socket.io”);

const http = require(“http”);

const userRoutes = require(“./Routs/UserRouts”);

const newsRoutes = require(“./Routs/NewsRouts”);

const app = express();

const server = http.createServer(app);

const io = socketio(server, {

cors: {

origin: "http://localhost:3000",

methods: ["GET", "POST"],

allowedHeaders: ["my-custom-header"],

credentials: true

}

});

app.use(express.json());

app.use(“/api/users”, userRoutes);

app.use(“/api/news”, newsRoutes);

io.on(“connection”, (socket) => {

console.log(“a user connected”);

// Emit an event to client to confirm connection

socket.emit(“connected”, { message: “You are connected!” });

// Listen for ‘news added’ event emitted by client

socket.on(“news added”, (data) => {

console.log(data);

// Do something with the new news data, e.g. save to database

// Emit 'news updated' event to all connected clients, including sender

io.emit("news updated", { message: "A new news item has been added!" });

});

// Listen for ‘disconnect’ event emitted by client

socket.on(“disconnect”, () => {

console.log("user disconnected");

});

});

const PORT = process.env.PORT || 5000;

mongoose

.connect(“mongodb://localhost:27017/firstFullstack”)

.then(() => {

console.log("Connected to database");

server.listen(PORT, () =>

  console.log(`Server is running on port: ${PORT}`)

);

})

import React, { useState, useEffect } from “react”;

import io from “socket.io-client”;

import {

Table,

TableBody,

TableCell,

TableContainer,

TableHead,

TableRow,

Paper,

} from “@mui/material”;

const socket = io(“http://localhost:5000/api/news”); // replace with your server URL

function NewsTable() {

const [news, setNews] = useState([]);

useEffect(() => {

socket.on("newsUpdate", (updatedNews) => {

  setNews(updatedNews);

});

return () => {

  socket.off("newsUpdate");

};

}, []);

return (

<TableContainer component={Paper}>

  <Table aria-label='news table'>

    <TableHead>

      <TableRow>

        <TableCell>Title</TableCell>

        <TableCell>News</TableCell>

        <TableCell>UserName</TableCell>

        <TableCell>Resurce</TableCell>

        <TableCell>Language</TableCell>

        <TableCell>Protection Level</TableCell>

        <TableCell>Priority</TableCell>

        <TableCell>Media</TableCell>

      </TableRow>

    </TableHead>

    <TableBody>

      {news.map((n) => (

        <TableRow key={n._id}>

          <TableCell>{n.Title}</TableCell>

          <TableCell>{n.News}</TableCell>

          <TableCell>{n.UserName}</TableCell>

          <TableCell>{n.Resurce}</TableCell>

          <TableCell>{n.Language}</TableCell>

          <TableCell>{n.ProtectionLevel}</TableCell>

          <TableCell>{n.priority}</TableCell>

          <TableCell>{n.Media}</TableCell>

        </TableRow>

      ))}

    </TableBody>

  </Table>

</TableContainer>

);

}

export default NewsTable;

const express = require(“express”);

const router = express.Router();

const newsmodel = require(“../models/News.model”);

const { body, validationResult } = require(“express-validator”);

const cors = require(“cors”);

router.use(cors());

// Socket.io integration

const server = require(“http”).createServer();

const io = require(“socket.io”)(server, {

cors: {

origin: "http://localhost:3000",

methods: ["GET", "POST"],

},

});

io.on(“connection”, (socket) => {

console.log(“A client has connected.”);

socket.on(“disconnect”, () => {

console.log("A client has disconnected.");

});

});

// get all news

router.get(“/”, async (req, res) => {

try {

const allnews = await newsmodel.find();

if (!allnews) {

  return res.status(404).json({

    Date: null,

    message: "users not found",

  });

}

res.status(200).json({ Date: allnews });

} catch (error) {

res.status(500).json({ Date: null, message: "News not found", error });

}

});

// get one

router.get(“/:id”, async (req, res) => {

try {

const oneuser = await newsmodel.findById(req.params.id);

if (!oneuser) {

  return res.status(404).json({

    Date: null,

    message: "news with id not found",

  });

}

res.status(200).json({ data: oneuser });

} catch (error) {

res

  .status(500)

  .json({ Date: null, message: "technical error", error });

}

});

// insert news post

router.post(“/add”, async (req, res) => {

try {

const addnews = await new newsmodel({

  Title: req.body.Title,

  News: req.body.News,

  UserName: req.body.UserName,

  Resurce: req.body.Resurce,

  Language: req.body.Language,

  ProtectionLevel: req.body.ProtectionLevel,

  priority: req.body.priority,

  Media: req.body.Media,

});

const newnews = await addnews.save();

io.emit("newsAdded", newnews);

res.json({ data: newnews, message: "news Added successfully" });

} catch (error) {

res

  .status(500)

  .json({ message: "An error occurred while adding the news user" });

}

});

// delete one

router.delete(“/:id”, async (req, res) => {

try {

const userfordelet = await newsmodel.findByIdAndDelete(req.params.id);

if (!userfordelet) {

  return res.status(404).json({ data: null, message: "News not Found" });

}

io.emit("newsDeleted", req.params.id);

res.status(200).json({ data: "News deleted successfully" });

} catch (error) {

res.status(500).json({ data: null, message: "Technical error", error });

}

});

// update news by id

router.put(“/:id”, async (req, res) => {

try {

const updatedNews = await newsmodel.findByIdAndUpdate(

  req.params.id,

  req.body,

  {

    new: true,

  }

);

if (!updatedNews) {

  return res.status(404).json({ data: null, message: "News not Found" });

}

res.status(200).json({ data: updatedNews, message: "News updated successfully" });

} catch (error) {

res

  .status(500)

  .json({ data: null, message: "Technical error", error: error });

}

});

module.exports = router;

i want to update data row automatically but data not show from data base

Audio Decoder And selection Features to be added in a video player

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Network Streaming Video Player</title>
 <style>
  #video-player {
   width: 100%;
   height: auto;
  }
 </style>
</head>
<body>
 <h1>Network Streaming Video Player</h1>
 <div>
  <label for="video-url">Video URL:</label>
  <input type="text" id="video-url" name="video-url" placeholder="Enter video URL">
  <button type="button" onclick="playVideo()">Play</button>
 </div>
 <video id="video-player" controls>
  <source id="video-source" type="vid`your text`eo/mp4">
    
 </video>
 <script src="https://cdn.dashjs.org/latest/dash.all.min.js"></script>
 <script>
  function playVideo() {
   var videoUrl = document.getElementById("video-url").value;
   var videoPlayer = document.getElementById("video-player");
   var videoSource = document.getElementById("video-source");

   videoPlayer.pause();
   videoSource.removeAttribute("src");
   if (videoUrl.endsWith(".mp4")) {
    videoSource.setAttribute("src", videoUrl);
    videoSource.setAttribute("type", "video/mp4");
   } else if (videoUrl.endsWith(".mpd")) {
    var player = dashjs.MediaPlayer().create();
    player.initialize(videoPlayer, videoUrl, true);
   } else if (videoUrl.endsWith(".mkv")) {
    var mse = new MediaSource();
    videoPlayer.src = URL.createObjectURL(mse);
    mse.addEventListener("sourceopen", function () {
     var sourceBuffer = mse.addSourceBuffer("video/webm; codecs="vp8, opus"");
     var mediaSource = new MediaSource();
     var videoUrlBlob = new Blob([videoUrl], { type: "video/webm" });
     var videoUrlBlobUrl = URL.createObjectURL(videoUrlBlob);
     fetch(videoUrlBlobUrl).then(function (response) {
      return response.arrayBuffer();
     }).then(function (videoData) {
      sourceBuffer.addEventListener("updateend", function () {
       mse.endOfStream();
       videoPlayer.play();
      });
      sourceBuffer.appendBuffer(videoData);
     });
    });
   }
   videoPlayer.load();
   videoPlayer.play();
  }`your text`
 </script>
</body>
</html>

This is my video player streaming websites where I can enter mkv mpeg URL and play the video. But,my main problem is that when I play dubbed video the video only plays its original audio. Even though when I try that URL in a network streaming apps, the video plays with a audio selection features like if a dubbed video has tamil english and hindi audio available in my video player only tamil audio is played and the rest audio language are not able to detect and neither can be select. Please can anyone help me with modifying this code and be able to select all the audio available in a video within a video player while playing a video.