Why is my slider animation not working transition-grope?

My animation for the slider is not working. I have used different examples of css styles, but still the transition for the slide does not work. When one of the buttons is pressed, I want to change the slide from right to left or from left to right. what am I doing wrong, who can tell?

 <template>
 <div class="sliderComponent">
     <transition-group  name="slide" tag="div" >
         <div v-for="(item, id ) in items" :key="id">
             <img :src="currentImage" title="image" :alt="item.id" class="slideImage">
         </div>
     </transition-group>
     <div class="controls">
         <button class="prev" @click="prevSlide">d</button>
         <button class="next" @click="nextSlide">b</button>
     </div>
 </div>
 </template>
  ______________
 <style>
 .slideImage {
 position: absolute;
 width: 100%;
 height: 100%;
 object-fit: cover;
  }

 .slider-enter-active,
 .slider-leave-active {
 transition: transform 0.5s;
 }

.slider-enter,
.slider-leave-to {
transform: translateX(-100%);
}
 </style>
   ```


Trigger dragenter on a container, not children

I have the following HTML, basically a div container having 100% of its surface covered with a header and a body.:

<div class="ui-layout--col">
  <div class="ui-layout--cell-container"> <!-- $0 -->
    <div class="ui-layout--panel-header-bar" draggable="true">
      <label>New panel</label>
    </div>
    <div class="ui-layout--panel-body">
      body
    </div>
  </div>
</div>

I want to listen to the dragenter and dragleave events on the container div, and apply a style to it when dragging over. The problem is, as I do this:

        $0.ondragenter = e => {
            console.log('enter', e.currentTarget, e.target)
            // e.target.style.opacity = '50%'
        }

It becomes evident that the event triggers on the container’s children (the header and the body), and not the container. So the event triggers multiple times within the same container, which causes issues.

Is there a way to listen to events only on the container and none of it’s children, even if the container is completely covered by the children?

How would you tackle this issue?

Thank you

Created upload function what works, but unable to return usestate from function

I have been trying to solve this for awhile and have reduced it to the barest minium I can, I have this page

import React, { useState } from "react"
import useUploader from "./uploaderexample"

function Uploadpage() {
  // Handles file selection
  const changeHandler = (e) => {
    setFiles(e.target.files)
  }

  // set use state for file selction
  const [files, setFiles] = useState()
  const [foldername, setFoldername] = useState("")

  return (
    <div>
      <input type="file" onChange={changeHandler} />
      <input type="text" onSubmit={setFoldername} placeholder="folder name" />
      <button
        className="bg-black text-white"
        onClick={() => useUploader(files, foldername)}
      >
        click here to upload
      </button>
      <div>
        return the status of upload here, this where I would like the status to
        be loaded from the useUploader function
      // this is a placeholder for conditional div
      <div>Successful upload</div>
      </div>
    </div>
  )
}
export default Uploadpage

A very simple page that allowes you to select files, name a folder and then upload it.

The useUploader looks like this:

import { ref, uploadBytesResumable } from "firebase/storage"
import { proStorage } from "./config"
import { useState } from "react"

// incoming data and name of folder to put them in for upload
const useUploader = (data, foldername) => {

  // set use state of outcome as a string
  const [upLoadcomplete, setuploacomplete] = useState("")

  //files and create folder on firebase
  const uploadFiles = async () => {
    // loop files
    for (let i = 0; i < data.length; i++) {
      //set folder
      const location = `${foldername}/filename`
      const dataRef = ref(proStorage, location)
      //upload 
      uploadBytesResumable(dataRef, data[i])
      // to keep simple imagine it works
      setuploacomplete['Success']

    }
  }

  // return the function and the outcome of the upload
  return [uploadFiles, upLoadcomplete]
}
export default useUploader

I have tried everything I can think og, however I am unable to fingure out how to make this work, I can return the uploadFiles function with no issues. However, when I try to return the upLoadcomplete, it causes an error

error when returning both

The only way I know how to fix this would be to not return the status, which is the opposite of what I am trying to do.

My flow would look like this:
Ideal flow

Essentially my issue is that I can’t return the function and also the string…(both are on seperate Jsx’s)

Any help?

How can I manage lengthy task functions in Node.js Express.js

How can I manage lengthy task functions in Node.js Express.js to manage lengthy task functions effectively, and prevent timeout errors? Presently, my application contains a time-consuming function, the response of which I don’t require immediately, but I still want it to execute its tasks. How can I ensure that I receive the API response while allowing the function to execute in the background?

const express = require('express');
const app = express();

async function performTask() {
   // Long Task Function 
}

app.get('/performTask', async (req, res) => {
  try {
    performTask();
    res.status(200).json({ message: "Function is called and it will do its job" });
  } catch (error) {
    res.status(500).json({ message: 'Error occurred', error });
  }
});

When I assemble an AST tree into a React component, the Cyrillic alphabet is converted to Unicode escape sequences

Actually, any text other than Latin does this.

I want to add an attribute “attrName” with a value “киррилица” to the button:
<button attrName="киррилица">текст</button>

But when i do parsing, add attribute and then generation i have this:
<button attrName="u043Au0438u0440u0440u0438u043Bu0438u0446u0430">текст</button>

It happens like this:

const generator = require('@babel/generator').default;
const { parse } = require('@babel/parser');
const traverse = require('@babel/traverse').default;


const code = `
import React from 'react';

export const Component = () => {
  return (
    <button>текст</button>
  );
};
`

const ast = parse(code, { sourceType: "module", plugins: ['jsx', 'typescript'] });

traverse(ast, {
  JSXOpeningElement(path) {
    const { attributes } = path.node || {};

    const newAttr = {
      type: 'JSXAttribute',
      name: {
        type: 'JSXIdentifier',
        name: 'attrName',
      },
      value: {
        type: 'StringLiteral',
        value: 'киррилица',
      },
    }

    attributes.push(newAttr)
  },
}, { scope: {} });

const options = { retainLines: true, comments: true };
const output = generator(ast, options, code).code;

console.log('output code: ', output);

I assume that the conclusion will be:

output code:  
import React from 'react';

export const Component = () => {
  return (
    <button attrName="киррилица">текст</button>);

};

But in the end I have this:

output code:  
import React from 'react';

export const Component = () => {
  return (
    <button attrName="u043Au0438u0440u0440u0438u043Bu0438u0446u0430">текст</button>);

};

Is it possible to leave the original text?

What is the correct way to do caching in Angular?

I am developing an app that receives a response from an API. I know that BehaviorSubject, SharedReplay and Share exist. To manage the cache, but I would like to know what is the correct and efficient way to manage the cache. I would like one that is fast and another that is efficient.

I am doing it with behaviorSubject

Fonts with format ttf are not loaded when I deploy mt react + vite project to vercel

I have built a vite + reactjs project and I use two fonts that are imported locally in index.css using font-face. everything works just fine in dev mode but when I do the npm run build and deploy my project on CPanel, fonts are not loaded. in the assets folder in the build file I can see the font-faces but for some reason they are not loaded correctly.

fonts are located in src/fonts;

index.css

@font-face {
  font-family: "IRANSans";
  src: local("IRANSans") , url("./fonts/IRANSans.ttf"), format('ttf');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: "Casablanca";
  src: local("Casablanca") ,url("./fonts/Casablanca.ttf"), format('ttf');
  font-weight: normal;
  font-style: normal;
}

then I import them in main.js(Vite)=> index.js(Reactjs) and everything seems correct but in production mode, fonts are not loaded! 🙁

Add google recapcha in next js 13

I have the following code block from my contact form build with Next js 13 with typescript.

"use client"
import { Button, Input, TextArea } from "@/components/atom"
import { z, ZodType } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState, useRef, RefObject } from "react"
import ReCAPTCHA from "react-google-recaptcha"

type FormData = {
  name: string
  email: string
  subject: string
  form_message: string
  captchaToken: string
}

const schema: ZodType<FormData> = z.object({
  name: z.string().min(5, { message: "Name is required" }),
  email: z.string().min(1, { message: "Email is required" }).email({
    message: "Must be a valid email",
  }),
  subject: z.string().min(5, { message: "Subject is required" }),
  form_message: z
    .string()
    .min(6, { message: "Message must be atleast 6 characters" }),
  captchaToken: z.string(),
})

const ContactForm = () => {
  const recaptcha: RefObject<ReCAPTCHA> = useRef(null)
  const [showToast, setShowToast] = useState(false)
  const [loading, setLoading] = useState(false)
  const [err, setErr] = useState(false)
  const {
    register,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(schema),
  })

  const submitData = async (data: FormData) => {
    try {
      setLoading(true)
      setErr(false)
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      })
      const res = await response.json()

      if (res.status === 200) {
        setShowToast(true)
      }
      recaptcha.current?.reset()
      setLoading(false)
      reset()
    } catch (e) {
      if (e) {
        setErr(true)
      }
      setLoading(false)
      setShowToast(true)
    }
  }

  useEffect(() => {
    if (showToast) {
      const timer = setTimeout(() => {
        setShowToast(false)
        setErr(false)
      }, 3000)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [showToast])

  const handleChange = (token: string | null) => {
    if (token) {
      setValue("captchaToken", token)
    }
  }
  return (
    <form onSubmit={handleSubmit(submitData)}>
      <div className="formRow flex gap-6">
        <Input
          label="Name"
          width="w-1/2"
          error={errors.name ? errors.name.message : null}
          placeholder="Full name"
          id="name"
          {...register("name")}
        />
        <Input
          label="Email"
          type="email"
          width="w-1/2"
          placeholder="Email address"
          id="email"
          error={errors.email ? errors.email.message : null}
          {...register("email")}
        />
      </div>
      <div className="formRow w-full gap-6">
        <Input
          label="Subject"
          placeholder="Subject"
          id="subject"
          error={errors.subject ? errors.subject.message : null}
          {...register("subject")}
        />
      </div>
      <div className="formRow w-full gap-6">
        <TextArea
          label="Message"
          placeholder="Message"
          id="form_message"
          rows={5}
          error={errors.form_message ? errors.form_message.message : null}
          {...register("form_message")}
        />
      </div>
      <div className="formRow flex gap-6">
        <ReCAPTCHA
          size="normal"
          sitekey="6Ldh6jgoAAAAAM44ieDQ6Nw1cvAWa5i2NhGjpV4a"
          onChange={handleChange}
          ref={recaptcha}
        />
      </div>
      <Button variant="primary" additionalClass="mt-5" submit loading={loading}>
        Send Message
      </Button>
      {showToast && (
        <div className="toast">
          <div className={`alert ${err ? "alert-danger" : "alert-success"}`}>
            <span>
              {err ? "Message sending failed" : "Message sent successfully!"}
            </span>
          </div>
        </div>
      )}
    </form>
  )
}
export default ContactForm

I’m using react-google-recaptcha package to add google recaptcha in the above contact form.

I’ve also installed type @types/react-google-recaptcha for the recaptcha. I followed this blog post tutorial to add recaptcha in my app.

In local (my pc) recaptcha is working fine. But when i deploy to vercel i’m getting build error. I’ve attached error message below:

Type error: 'ReCAPTCHA' cannot be used as a JSX component.
  Its type 'typeof ReCAPTCHA' is not a valid JSX element type.
    Type 'typeof ReCAPTCHA' is not assignable to type 'new (props: any, deprecatedLegacyContext?: any) => Component<any, any, any>'.
      Construct signature return types 'ReCAPTCHA' and 'Component<any, any, any>' are incompatible.
        The types returned by 'render()' are incompatible between these types.
          Type 'import("/vercel/path0/node_modules/@types/react-dom/node_modules/@types/react/index").ReactNode' is not assignable to type 'React.ReactNode'.
            Type 'ReactElement<any, string | JSXElementConstructor<any>>' is not assignable to type 'ReactNode'.
              Property 'children' is missing in type 'ReactElement<any, string | JSXElementConstructor<any>>' but required in type 'ReactPortal'.
  128 |       </div>
  129 |       <div className="formRow flex gap-6">
> 130 |         <ReCAPTCHA
      |          ^
  131 |           size="normal"
  132 |           sitekey="6Ldh6jgoAAAAAM44ieDQ6Nw1cvAWa5i2NhGjpV4a"
  133 |           onChange={handleChange}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1

I’ve also looked into the package documentation and couldn’t find the solution. Is my setup wrong or this package incompatible with next js typescript ? I would be thankful if anyone could point it out.

sweet alert error unable to work inside external php file

I have the html file and php file. The php file is used to process form data, in this case being to submit data to the database. I want to display sweet alert success message. I need help on how to do it. the provided responses on other post did not work for me.
below is my html code in its file :

<?php
include_once('../shared/header.php');
include_once('../shared/public.navbar.php');
include_once('../db/dbConnection.php');
include_once('../controllers/signupCpntroller.php');

?>

<body>
<section class="vh-100" style="margin-top:5%;" >
  <div class="container h-100">
    <div class="row d-flex justify-content-center align-items-center h-100">
      <div class="col-lg-12 col-xl-11">
        <div class="card text-black" style="border-radius: 25px;">
          <div class="card-body p-md-5">
            <div class="row justify-content-center">
              <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1">

                <p class="text-center h3 fw-bold mb-5 mx-1 mx-md-4 mt-4">Company Registration</p>
        
                <form class="mx-1 mx-md-4" name="formValidation" id="formValidation" action="../controllers/signupController.php" method="post">

                  <div class="d-flex flex-row align-items-center mb-4">
                  <i class="fa fa-user fa-lg me-3 fa-fw" aria-hidden="true"></i>
                    <div class="form-outline flex-fill mb-0">
                      <input type="text" id="companyName" name="company_name" class="form-control" placeholder="Enter Company Name" required/> 
                    </div>
                  </div>

                  <div class="d-flex flex-row align-items-center mb-4">
                  <i class="fa fa-envelope  fa-lg me-3 fa-fw" aria-hidden="true"></i>
                    <div class="form-outline flex-fill mb-0">
                      <input type="email" id="companyEmail" name="company_email" class="form-control" placeholder="Enter Company Email" required />
                    </div>
                  </div>

                  <div class="d-flex flex-row align-items-center mb-4">
                  <i class="fa fa-map-marker fa-lg me-3 fa-fw" aria-hidden="true"></i>
                    <div class="form-outline flex-fill mb-0">
                      <input type="text" id="companyLocation" name="company_location" class="form-control" placeholder="Enter Company Location" required />
                    </div>
                  </div>
                 
                  <div class="d-flex flex-row align-items-center mb-4">
                  <i class="fa fa-user fa-lg me-3 fa-fw" aria-hidden="true"></i>
                    <div class="form-outline flex-fill mb-0">
                      <input type="text" id="subscription" name="subscription" class="form-control" placeholder="Enter Subscription" required/>
                    </div>
                  </div>

                  <div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
                    <input type="submit" class="btn btn-primary btn-lg" name="submit" value="Create Account"/>
                  </div>
                </form>
                <div class="form-check d-flex justify-content-center mb-5">
                     <p>Already have an Account?  <a href="../auth/login.php"> Sign in</a></p>
                  </div>
              </div>
              <div class="col-md-10 col-lg-6 col-xl-7 d-flex align-items-center order-1 order-lg-2" style="margin-top: -10%;">

                <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-registration/draw1.webp"
                  class="img-fluid" alt="Sample image">

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="../js/custom.js"></script>
<script>
        // Call the function after the page is loaded
        window.onload = function() {
            myFunction(); // Call the JavaScript function
        };
    </script>
</body>

<?php
include_once('../shared/footer.php');
?>

below is my php code in its file:

<?php
include_once('../db/dbConnection.php');

$company_name = $_POST["company_name"];
$company_email = $_POST["company_email"];
$company_location = $_POST["company_location"];
$subscription = $_POST["subscription"];

$sql = "INSERT INTO company (company_name, company_email, company_location, subscription)
        VALUES (?, ?, ?, ?)";

$stmt = mysqli_stmt_init($dbConnection);

if (! mysqli_stmt_prepare($stmt, $sql)){
    die(mysqli($dbConnection));
}

mysqli_stmt_bind_param($stmt, "ssss",
                       $company_name,
                       $company_email,
                       $company_location,
                       $subscription );

mysqli_stmt_execute($stmt);

echo "company registration successful"; 

?>

all I need is way on how to return sweet alert dialogs after a form was submitted

why is “chrome.cookies.get” not existant?

so i’m just making a roblox extension for avatars and i apparently needed to get the cookie to actually load in the avatar. here’s my function:

    function rasc_saveCode() {
        alert("Saving code...");
        

        var promisedCoki = chrome.cookies.get({ name: ".ROBLOSECURITY", url: "*://*.roblox.com/" }, (cookie)=>{
            alert(cookie.value);
        });
    }

and here’s my manifest:

{
    "manifest_version": 3,
    "name": "Roblox Avatar Save&Load",
    "version": "1.0",
    "description": "Share an avatar with friends",
    "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "48": "images/icon-48.png",
        "64": "images/icon-64.png",
        "128": "images/icon-128.png"
    },
    "host_permissions": [
        "*://*.roblox.com/*"
    ],
    "permissions": [
        "cookies"
    ],
    "content_scripts": [
        {
            "js": ["userscript.js"],
            "matches": [
                "*://*.roblox.com/*"
            ]
        }
    ]
}

and also my developer console errors:
developer console errors

can somebody help me figure out why this doesnt work?

(one note: this is a duplicate im just becoming more specific to my code and also the duplicate doesnt have any solutions yet)

i was expecting to see my full roblox cookie in an alert message to see if grabbing the user’s cookie worked for buying the items for loading an avatar

How do i resolve this error when requesting JSON from Flask back end?: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Im currently creating an app that uses python to send a dictionary to my React front end using Flask. Even though I’m returnng valid JSON from my back end, my front end also shows this error:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

Any help would be much appreciated!

This is the server.py

from flask import Flask

app = Flask(__name__)

@app.route("/members")
def members():
    return {"members": ["Member1","Member2","Member3"]}

if __name__ == "__main__":
    app.run(debug=True)

This is the App.js

import React, {useState, useEffect} from 'react'

function App() {

  const [data, setData] = useState([{}])

  useEffect(() => {
    fetch("/members").then(
      res => res.json()
    ).then(
      data => {
        setData(data)
        console.log(data)
      }
    )
  }, [])

  return (
    <div>

    </div>
  );
}

export default App;


This is the index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);


Upon running the code, this ALWAYS gives the following error:

Uncaught runtime errors:
ERROR
JSON.parse: unexpected character at line 1 column 1 of the JSON data
ERROR
JSON.parse: unexpected character at line 1 column 1 of the JSON data

Returning correct result not passing test [duplicate]

I’m in a class where the assignment is similar to fizz/buzz. My code is returning the correct result but not passing the inline tests.

I have tried everything I know to fix this. This includes changing the parameter name and adding a let statement before the for statement. I have tried moving the return to just under the function, closing the function and keeping the let outside the function.

I just don’t know. There are four tests and it returns true only on the else { return (i) I have switched the “console.log” to return and both with and without the parenthetics it breaks the code altogether. I have dread just about every other question on let and for statements over the last nine days and nothing helps. Yet everytime I post stack overflow closes the question and gives me a “similar” question that a) doesn’t reflect my question or b) is written in such a convoluted way that its incomprehensible to me.

function simplifiedFizzBuzz(fizz) {
  for (let i = 1; i <= 15; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      console.log("FizzBuzz")
    } else if (i % 3 === 0) {
      console.log("Fizz")
    } else if (i % 5 === 0) {
      console.log("Buzz")
    } else {
      console.log(i)
    }

  }
  return fizz
  console.log(simplifiedFizzBuzz(fizz))
}

I have

While loop practice [closed]

I am trying to use a while loop to change the background-color of some h1‘ s.
I know that there can be only one H1 on the page but is not what i am try to practice.
The code that I wrote works but when I open the console I still get an error.

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>While loop</title>

  <style>
    .red{
      color:red
    }
  </style>

</head>
<body>
  <h1 class="red">heading01</h1>
  <h1>heading02</h1>
  <h1 class="red">heading03</h1>
  <h1>heading04</h1>
  <h1 class="red">heading05</h1>


  <script>
    function changeColor(){
      const heading = document.querySelectorAll("h1");
      let i = 0;
      while (i <= heading.length){
        if (!heading[i].classList.contains("red")){
          heading[i].style.backgroundColor = "lightgreen";
        }
        i++;
      }
    }

    changeColor();

  </script>
</body>
</html>

index1.html:27 Uncaught TypeError: Cannot read properties of undefined (reading 'classList') at changeColor (index1.html:27:25) at index1.html:34:5

Can anyone tell me why it is giving me that error?
Thank you.

I tried to go step by step with a console.log() to see what is happening.

Also I tried it with a For Of loop and that works with no errors.

Google Drive API problem connecting with NodeJS

I am trying to create a gallery page in my NodeJS app. However, there it seems like something isn’t working with the connection. The idea is to get all photos from a Google Drive folder that is public. I enabled Google Drive API and connected it with the NodeJS app. Despite all that, if I go to /gallery where the images should be displayed ejs doesn’t get any images and throws an error. I include the server.js code and the gallery.ejs code:

Server.js

const express = require('express');
const sendEmail = require('./public/JS/sendEmail');
const fs = require('fs');
const path = require('path');
const { google } = require('googleapis'); // Add this line to import Google API client

const app = express();
const port = 3000;

app.use(express.static('public'));

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.urlencoded({ extended: true }));

const routesDir = path.join(__dirname, 'routes');
fs.readdirSync(routesDir).forEach((file) => {
  if (file.endsWith('.js')) {
    const route = require(path.join(routesDir, file));
    app.use(`/${file.replace('.js', '')}`, route);
  }
});

app.get('/', (req, res) => {
  res.render('index', { data: 'Data here...' });
});

app.get('/gallery', async (req, res) => {
  try {
    // Create a Google Drive API client
    const drive = google.drive({ version: 'v3' });

    const folderId = '1agwyqLRDj4t_PsF9IOZfDdObrtJ3Ti7X';

    // List all photos in the specified folder
    const response = await drive.files.list({
      q: `'root' in parents and (mimeType='image/jpeg' or mimeType='image/png' or mimeType='image/gif')`,
      fields: 'files(id, name, webViewLink)',
    });

    const photos = response.data.files;
    console.log(photos); // Won't console.log the photos
    res.render('gallery', { photos }); // Render the gallery page with photos
  } catch (err) {
    console.error('Error fetching photos from Google Drive:', err);
    res.status(500).send('Internal Server Error');
  }
});


// Nodemailer
app.post('/send', (req, res) => {
  sendEmail(req.body)
    .then((info) => {
      const currentURL = `${req.protocol}://${req.get('host')}`;
      res.redirect(`${currentURL}/contacts?success=true`);
    })
    .catch((err) => {
      const currentURL = `${req.protocol}://${req.get('host')}`;
      res.redirect(`${currentURL}/contacts?success=false`);
    });
});

app.listen(port, '0.0.0.0', () => {
  console.log(`Server running at port:${port}`);
});

gallery.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="/styles/footer.css" />
    <link rel="stylesheet" href="/styles/global.css" />
    <link rel="stylesheet" href="/styles/responsive/nav.css" />
    <link rel="stylesheet" href="/styles/nav.css" />
    <link rel="stylesheet" href="/styles/responsive/footer.css" />
    <link rel="stylesheet" href="/styles/loadingScreen.css" />
    <link rel="stylesheet" href="/styles/gallery.css">
    <link rel="shortcut icon" href="/img/logo.png" />
    <title>Gallery</title>
</head>
<body>
    <%-include ('partials/loading-screen') %>
    <%-include ('partials/header') %>
    
<h1 class="main-heading">Gallery</h1>

<div class="photo-container">
    <% photos.forEach(photo => { %>
      <a href="<%= photo.webViewLink %>" target="_blank">
        <img src="<%= photo.webViewLink %>" alt="<%= photo.name %>" />
      </a>
    <% }) %>
  </div>

    

    <%-include ('partials/footer') %>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js"></script>
    <script src="/JS/mobileMenu.js"></script>
    <script src="/JS/loadingAnimation.js"></script>
</body>
</html>

Is there a way to encode an audio Blob from the MediaRecorder API in LINEAR16?

I want to send audio directly from the mic of the user to the Google Speech To Text API in realtime. So I would like to use its RecognizeStream feature.

To do this, I use the MediaRecorder API on a webpage, that is connected to my NodeJS server via websockets.
Every 2 seconds, I get an audio blob via the ondataavailable event from the MediaRecorderAPI, and I send it to my server via websockets. Then, my server send the blob to the Speech To Text API using the google library with the recognizeStream.write(blob). But right now, the API returns nothing and timeout. I read that it was because of the encoding.

The problem is that I am new to audio encoding and I can’t find a way to convert the original blob, to a LINEAR16 blob without using physical files. I’d like to do it directly in the code, because I want to reduce latency as much as possible.

I tried to use the Sox software with the npm package to do the conversion but it can’t find a way to use it without physical files.

Here is the frontend code that allows me to send data to the backend.

const mediaConstraints = { audio: true };

mediaStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
mediaRecorder = new MediaRecorder(mediaStream);
let isRecording = false;

mediaRecorder.ondataavailable = (event) => {
     if (isRecording && event.data.size > 0) {
             socket.emit('audioChunk', event.data);
     }
};

Here is some parts of my NodeJS backend.

const encoding = 'LINEAR16';
const languageCode = 'fr-FR';
const sampleRateHertz = 16000;

const request = {
  config: {
    encoding: encoding,
    languageCode: languageCode,
    sampleRateHertz: sampleRateHertz,
  },
  interimResults: true, // If you want interim results, set this to true
};



io.on('connection', (socket) => {
  console.log('A user connected');

  const recognizeStream = client
  .streamingRecognize(request)
  .on('error', console.error)
  .on('data', data =>
    process.stdout.write(
      data.results[0] && data.results[0].alternatives[0]
        ? `Transcription: ${data.results[0].alternatives[0].transcript}n`
        : 'nnReached transcription time limit, press Ctrl+Cn'
    )
  );

  socket.on('audioChunk', (chunk) => { 
    const blob = new Blob([chunk], {type: 'audio/webm;codecs=opus'});
    // CONVERSION NEEDED
    recognizeStream.write(blob.binaryData);
  });