Javascript is not waiting for async function to complete

I have this async function:

export const GetSearchQueryResults = async (gqlEndpoint: string, gqlApiKey: string, query: string): Promise<any> => {
  console.log(query);
  fetch(gqlEndpoint, {
    method: 'POST',
    headers: new Headers({ sc_apikey: gqlApiKey, 'content-type': 'application/json' }),
    body: query,
  })
    .then((response) => response.json())
    .then((data) => {
      // parse data
      console.log('Results: ');
      const results = data.data.pageOne;
      console.log(results);
      return results;
    })
    .catch((error) => {
      console.log(error);
    });
};

and I’m calling it from another function:

const data = GetSearchQueryResults(gqlEndpoint, gqlApiKey, query).then((data) => {
   console.log('Awaited results:');
   console.log(data);
});

but no matter what I try, the “awaited results” are logging as undefined before the function async function actually completes. I can tell because looking at the console, I see

"Awaited results:"
undefined
"Results:"
{results obj}

So I know that the fetch is in fact getting data, but GetSearchQueryResults is executing the then before the async function actually finishes. What am I doing wrong?

Custom Express Middleware resulting in TypeError: app.use() requires a middleware function

const ErrorHandler = (err, req, res, next) => {
    logging.error(err);
    let message = 'An error occured, please try again.';
    let statusCode = 500;

    const response = {
        success: false,
        message: message,
    };

    
    res.status(statusCode).json(response);
    //  in the future add custom error messages based on error type 
};

export default ErrorHandler;

The above is my custom middleware. I have appropiately imported it on my main app.js file using:

const ErrorHandler = require('./middleware/ErrorHandler');
app.use(ErrorHandler);

And my post route looks like:

router.post('/submit-recipe', getUserMiddleware, upload.any(), async (req, res, next) => {

I have followed along some other posts such as this one, and all my routers are correctly being exported/imported.

Am I missing something obvious here?

Detecting whether the device that a JS web script is running on has accelerometers available for devicemotion/deviceorientation access

I’m trying to detect whether a device that’s running a webpage JavaScript script in a browser has accelerometer data available for devicemotion and deviceorientation access. This is what I have now:

  function onMotion(event) {
    if (event.acceleration.y==null) {
      //there can be null events even on supported devices
      return;
    }
    document.getElementById("support-status-text").innerHTML = "Supported on this device";
    document.getElementById("y-acceleration-text").innerHTML = roundToFixed(event.acceleration.y);
  }

  function roundToFixed(value) {
    return value==null ? value : value.toFixed(2);
  }

  if (!('ondeviceorientation' in window)) {
    document.getElementById("support-status-text").innerHTML = "Orientation not supported on this device";
  }

  if ('ondevicemotion' in window) {
    window.addEventListener('devicemotion', onMotion);
  } else {
    document.getElementById("support-status-text").innerHTML = "Not supported on this device";
  }
<div id="container">
  <p id="support-status-text">Loading...</p>
  <p id="y-acceleration-text">nothing</p>
</div>

On my phone, which has both motion and orientation support, the top text reads “Supported on this device” with the incoming accelerometer data displayed below it (after flashing “Loading…” and “nothing” before non-null events start firing, which is fine for now). However, on my laptop, which does not have motion support, I just see “Loading…” rather than the expected “Not supported on this device”. On my tablet, which I believe has motion support but not orientation support, I see “Loading…” rather than the expected “Orientation not supported on this device”. What am I doing wrong?

How to load file in ffmpeg in chunks?

I’m having a problem when loading a larger file with ffmpeg in safari mobile, it crashes while doing that.

Currently I’m loading the whole file at once await ffmpeg.writeFile(inputFileName, await fetchFile(file)); and to my understanding safari tries to load it in-memory in one go and fails.

How can I work around this issue? Maybe split the file to chunks? Maybe streaming?

Thank you.

How group-by and count/sum over JSON data using JSONATA in a web page

Today i spent all hours with this problem: i would group by and count over json data using JSONata.

This is my json data

var mydata = [
{"OWNED": "A","DOSSIER": "Private","DIP_ID": 8619},
{"OWNED": "B","DOSSIER": "Public", "DIP_ID": 17},
{"OWNED": "C","DOSSIER": "Private","DIP_ID": 27635},
{"OWNED": "A","DOSSIER": "Public","DIP_ID": 111},   
{"OWNED": "B","DOSSIER": "Public","DIP_ID": 110}
];

I would obtain a javascript variable with folowing result data:

grouping on OWNED and DOSSIER fields
and counting DIP_ID field for each group.

I’ve used following approach:

var expr = ‘{“counter”: $count(DIP_ID), “sku”:$distinct(OWNED)}’;

var result = await jsonata(expr).evaluate(mydata);

I can’t understand how make an expression to pass to jsonata function.

I’ve tried to adapt the following examples but i receive always an error from javascript library
jsonata.min.js

Probably i can’t able to make a string with corrected syntax inside var “expr”.

Example
Example 2

Maybe the main problem is understand how integrate JSONata query language in my javascript file.

Thanks in advance.

Attach Add-in to word/excel document from Angular application

We have two Add-Ins that were developed with VB script, one each for word document and excel document. These Add-Ins do some background work to replace placeholders in the template with the corresponding values provided.

We have an Angular application where user selects a word or excel template, at that time, the above mentioned Add-In based on the template type needs to be added/attached to the template.

I know how to create Add-in through Angular code, however, I don’t know how to attach/add Add-in to the templates through Angular code.

Is it possible to attach an existing Add-in to the template in Angular application?

i try to make text to speech extension with some pause and resume feature got error message “The message port closed before a response was received.”

i want to make pause and resume function in the same button, but the error message indicate that the port was closed. i assume that the sendMessage failed to send a message to my background.js like the error literally said, or the speechSynthesis status like speaking, paused, etc only updated on readSelectedText() function.

here is my background.js:

let isPaused = false;
let currentUtterance = null;
   
function readSelectedText(text) {
  chrome.storage.sync.get(["selectedVoice", "selectedRate", "selectedVolume"], (data) => {
    if (speechSynthesis.speaking) {
      speechSynthesis.cancel(); 
      
      console.log("read text:", text, speechSynthesis.speaking);
    }

    let utterance = new SpeechSynthesisUtterance(text);
    let voices = speechSynthesis.getVoices();

    if (data.selectedVoice) {
      let selectedVoice = voices.find(v => v.name === data.selectedVoice);
      if (selectedVoice) {
        utterance.voice = selectedVoice;
      }
    }

    utterance.rate = data.selectedRate || 1.0;
    utterance.volume = data.selectedVolume !== undefined ? data.selectedVolume : 1.0;

    // Event listener for update status
    utterance.onstart = () => {
      isPaused = false;
      chrome.storage.sync.set({ isPaused: false, isSpeaking: true });
      console.log("im on start");
    };

    utterance.onpause = () => {
      isPaused = true;
      chrome.storage.sync.set({ isPaused: true });
      console.log("im onpause");
    };

    utterance.onresume = () => {
      isPaused = false;
      chrome.storage.sync.set({ isPaused: false });
      console.log("im onresume");
    };

    utterance.onend = () => {
      isPaused = false;
      chrome.storage.sync.set({ isPaused: false, isSpeaking: false });
      console.log("im onend");
    };

    speechSynthesis.speak(utterance);
    console.log("read text:", text, speechSynthesis.speaking);
  });
  
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // console.log("reciving request action:", request.action);

  if (request.action === "pauseSpeech") {
      if (!speechSynthesis.paused) {
          // speechSynthesis.pause();
          speechSynthesis.pause();
          chrome.storage.sync.set({ isPaused: true });
          sendResponse({ status: "paused" }); 
          // return true;
      } else {
          console.log("on pause.");
          sendResponse({ status: "already_paused" });
          // return true;
      }
      
  } 
  else if (request.action === "resumeSpeech") {
      if (speechSynthesis.paused) {
          speechSynthesis.resume();
          chrome.storage.sync.set({ isPaused: false });
          sendResponse({ status: "resumed" }); 
          // return true;
      } else {
          console.log("playing.");
          sendResponse({ status: "already_playing" });
          // return true;
      }
  }
  
  return true; 
});

here is my voice.js:


  const pauseSpeech = document.getElementById("pauseSpeech");
  const status = document.getElementById("status");
  const data = document.getElementById("data");
  
  pauseSpeech.addEventListener("click", () => {
    console.log("aku paused click");
    // speechSynthesis.pause();
    chrome.storage.sync.get(["isPaused"], (result) => {
        if (!result.isPaused) {
            console.log("im if click");
            chrome.runtime.sendMessage({ action: "pauseSpeech" }, (response) => {
                if (chrome.runtime.lastError) {
                  data.innerText = `
                  Error sending message:, ${chrome.runtime.lastError.message}`;
                  return true;
                } else {
                    data.innerText = `Status: ${response.status}`;
                  return true;
                }
            });
        } else {
            // speechSynthesis.resume();
            chrome.runtime.sendMessage({ action: "resumeSpeech" }, (response) => {
                if (chrome.runtime.lastError) {
                  data.innerText = `
                  Error sending message:, ${chrome.runtime.lastError.message}`;
                  console.log("im else");
                  return true;
                } else {
                    data.innerText = `Status: ${response.status}`;
                    return true;
                }
            });
        }
        return true;
    });
});

what im expecting is when user right click the selected phrase then click contextMenu “read selected” the selcted text get readed with speechSynthesis and when user click pause button the speechSynthesis get paused and if the user click pause button again the speechSynthesis get resume.

i already tried giving speechSynthesis.pause() and resume directly in voices.js the pause function is working but not the resume, here’s what it’s like:

pauseSpeech.addEventListener("click", () => {
     console.log("pauseSpeech");
     if (!isPaused) {
         speechSynthesis.pause();
         isPaused = true;
         data.innerText = `
         Speaking: ${speechSynthesis.speaking},
         Paused: ${speechSynthesis.paused},
         Pending: ${speechSynthesis.pending}.`;
     } else{
         speechSynthesis.resume();
         isPaused = false;
         data.innerText = `
         Speaking: ${speechSynthesis.speaking},
         Paused: ${speechSynthesis.paused},
         Pending: ${speechSynthesis.pending}.`;
     }
 });

DIV flickering during transition when under Navigation Bar

const flipCards = document.querySelectorAll('.flip-card');
const viewMoreButtons = document.querySelectorAll('#view-more-details-button');
const viewSummaryButtons = document.querySelectorAll('#view-summary-button');

// Loop through the buttons and add event listeners
viewMoreButtons.forEach((button) => {
  button.addEventListener('click', function() {
    // Get the flip-card-inner element that corresponds to the button clicked
    const flipCardInner = button.closest('.flip-card').querySelector('.flip-card-inner');

    // Toggle the 'flipped' class to trigger the flip effect
    flipCardInner.classList.toggle('flipped');
  });
});

viewSummaryButtons.forEach((button) => {
  button.addEventListener('click', function() {
    // Get the flip-card-inner element that corresponds to the button clicked
    const flipCardInner = button.closest('.flip-card').querySelector('.flip-card-inner');

    // Remove the 'flipped' class to trigger the flip effect
    flipCardInner.classList.remove('flipped');
  });
});
html,
body {
  margin: 0 0 200px 0;
  padding: 0;
}

body {
  background: white;
  overflow-x: hidden;
}

/* Nav Bar */

nav {
  font-size: 1.25rem;
  height: 5rem;
  z-index: 999;
  position: sticky;
  top: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: lightblue;
  padding: 0 6rem;
  width: 100vw;
  box-sizing: border-box;
}


#nav-logo {
  height: 40px;
  font-family: "Roboto";
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  flex-grow: 1;
}

nav li {
  display: flex;
  align-items: center;
  padding: 0px 2rem;
}

nav a {
  text-decoration: none;
  transition: 0.2s ease;
}


#nav-name {
  font-size: 36px;
  font-weight: 800;
  font-family: "Roboto";
}

#contact-nav {
  color: white;
  padding: 1.1rem;
}



#card h1 {
  font-size: 3.5rem;
  margin: 4rem 0 4rem 0;
}

.style-card h1 {
  margin-top: 0 !important;
}

#card {
  width: 100vw;
  height: auto;
  background: white;
  margin-bottom: 5rem;
}

#card-grid {
  display: inline-flex;
  flex-direction: row;
  justify-content: center;
  width: 90vw;
  grid-gap: 1px;
}

.style-card {
  background-color: transparent;
  /*#a2b1bd;*/
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: column;
  width: 24%;
  aspect-ratio: 1/1.3;
}


#card h3 {
  margin: 0;
}

#card img {
  background-color: transparent;
  border-radius: 1rem;
  width: 96px;
  height: 96px;
}


.style-card ul {
  list-style-type: "> ";
  width: 60%;
  margin: 0;
}

.style-card li {
  padding: .55rem 0;
}

.style-card button {
  border: none;
  padding: 1rem 0;
  border-radius: 15rem;
  color: white;
  width: 60%;
  font-size: 1.01rem;
  background-color: black;
  transition: 0.2s ease;
}

.style-card button:hover {
  cursor: pointer;
  background-color: #2834b5;
}


.banner {
  width: 100%;
  margin: 0 !important;
  text-align: center;
  font-size: 1.2rem;
  color: white;
  border-radius: 16px 16px 0 0;
  margin: 0;
  padding: .5rem 0;
  margin-bottom: -1.25rem;
  top: 0;
  left: 0;
  z-index: 2;
  background-color: transparent;
  height: 1rem;
  position: absolute;
  top: 0;
  left: 0;
  height: auto;
}

#highlighted-banner {
  background-color: red;
  color: white;
}

.grow-box {
  flex-grow: 1;
}


/*card flip*/
.flip-card {
  perspective: 1000px;
  /* Remove this if you don't want the 3D effect */
}

/* This container is needed to position the front and back side */
.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */
.flipped {
  transform: rotateY(180deg);
}

/* Position the front and back side */
.flip-card-front,
.flip-card-back {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  /* Safari */
  backface-visibility: hidden;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: column;
  border-radius: 16px;
  z-index: 1;
}

/* Style the front side (fallback if image is missing) */
.flip-card-front {
  background-color: white;
  border: 1px #DDDDDD solid;
  color: black;
}

/* Style the back side */
.flip-card-back {
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}
<nav>
  <p id="nav-name">Logo Here</p>
  <ul>
    <li><a href="">Home</a></li>
    <li><a href="">About</a>
    <li><a href="">Blog</a></li>
    <li><a href="">FAQ</a></li>
  </ul>
  <button id="contact-nav">Contact</button>
</nav>

<div id="card" class="center-container">
  <h1>Displaying flippable cards</h1>
  <div id="card-grid">
    <div class="flip-card style-card hidden">
      <div class="flip-card-inner">
        <div class="flip-card-front">
          <p class="banner" id="highlighted-banner">Put the bottom edge of the blue nav bar half way over this banner to see effect</p>
          <img src="https://em-content.zobj.net/source/apple/391/high-voltage_26a1.png">
          <h3>Title</h3>
          <p>Front of Card</p>
          <ul>
            <li>Example 1</li>
            <li>Example 2</li>
            <li>Example 3</li>
            <li>Example 4</li>
            <li>Example 5</li>
            <li>Example 6</li>
            <li>Example 7</li>
            <li>Example 8</li>
          </ul>
          <div class="grow-box"></div>
          <button id="view-more-details-button">View More Details</button>
        </div>
        <div class="flip-card-back">
          <h1>John Doe</h1>
          <p>Architect & Engineer</p>
          <p>We love that guy</p>
          <button id="view-summary-button">View Summary</button>
        </div>
      </div>
    </div>
  </div>
</div>

I am trying to implement this Card Flipping effect from W3Schools (https://www.w3schools.com/howto/howto_css_flip_card.asp) into my current project but I’m only having issues with the transition when the Card is under the Navigation Bar.

If you scroll the blue Navigation Bar so the bottom edge covers the Red Banner of the Card then press the button to start the animation, the top half of both sides of the Card will begin to flicker. If you cover the entire banner or none of the banner with the Navigation Bar then the transition on looks and works fine. Why does this happen and how would I go about fixing this?

How to Eagerly Load Related Model Without TypeScript Error

I want to eagerly load a related aws-amplify gen 2 model and pass it on, but it seems to cause a typescript error no matter what I try. How do I do this without causing a typescript error?
For background, I’ve done JavaScript, Python and dabbled in others but I’m new to TypeScript and Amplify. I’m using the web/ChatGPT to figure it out but neither seemed to help with this question.

The Error

Types of property 'dataType' are incompatible.
        Type '{ name: string; isComplex: boolean; dataCategories: LazyLoader<{ name: string; addDefault: boolean; dataEntries: LazyLoader<{ category: LazyLoader<... | null, false>; dataCategoryId: string; ... 7 more ...; readonly updatedAt: string; } | null, true>; ... 9 more ...; readonly updatedAt: string; } | null, true>; note...' is not assignable to type 'LazyLoader<{ name: string; isComplex: boolean; dataCategories: LazyLoader<{ name: string; addDefault: boolean; dataEntries: LazyLoader<{ category: LazyLoader<... | null, false>; dataCategoryId: string; ... 7 more ...; readonly updatedAt: string; } | null, true>; ... 9 more ...; readonly updatedAt: string; } | null, ...'.
          Type 'undefined' is not assignable to type 'LazyLoader<{ name: string; isComplex: boolean; dataCategories: LazyLoader<{ name: string; addDefault: boolean; dataEntries: LazyLoader<{ category: LazyLoader<... | null, false>; dataCategoryId: string; ... 7 more ...; readonly updatedAt: string; } | null, true>; ... 9 more ...; readonly updatedAt: string; } | null, ...'.

The Set Up

api.ts

/**
 * Subscribe to real-time updates for data categories, including their data types.
 * @param {Function} callback - Function to update state with new data.
 * @returns {Function} Unsubscribe function.
 */
export function subscribeToDataCategories(
  callback: (items: Schema["DataCategory"]["type"][]) => void
): () => void {
  const sub = client.models.DataCategory.observeQuery().subscribe({
    next: async (result: { items?: Schema["DataCategory"]["type"][] }) => {
      console.log("Updating DataCategories:", result.items);

      if (!result.items) {
        callback([]);
        return;
      }

      const enrichedItems = await Promise.all(
        result.items.map(async (item) => {
          try {
            let dataType: Schema["DataType"]["type"] | undefined;

            if (item.dataType && typeof item.dataType === "function") {
              // Resolve LazyLoader
              const resolved = await item.dataType();
              dataType = resolved?.data ?? undefined;
            }

            return { ...item, dataType };
          } catch (error) {
            console.error(
              `Failed to fetch DataType for ID ${item.dataTypeId}:`,
              error
            );
            return { ...item };
          }
        })
      );

      console.log("Enriched Categories:", enrichedItems);

      callback(enrichedItems);
    },
    error: (error: unknown) => {
      console.error("Subscription error:", error);
    },
  });

  return () => sub.unsubscribe(); // Cleanup function
}

resources.ts

Here is my resources.ts file

import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
import { postConfirmation } from "../auth/post-confirmation/resource";

const schema = a
  .schema({
    UserProfile: a
      .model({
        email: a.string().required(),
        profileOwner: a.string(),
      })
      .secondaryIndexes((index) => [index("email")])
      .authorization((allow) => [
        allow.owner(),
        allow.ownerDefinedIn("profileOwner"),
        allow.groups(["Admins"]).to(["read"]),
      ]),
    DataType: a
      .model({
        name: a.string().required(),
        note: a.string(),
        isComplex: a.boolean().required(),
        dataCategories: a.hasMany("DataCategory", "dataTypeId"),
      })
      .secondaryIndexes((index) => [index("name")])
      .authorization((allow) => [allow.authenticated(), allow.publicApiKey()]),
    DataCategory: a
      .model({
        name: a.string().required(),
        note: a.string(),
        addDefault: a.boolean().required(),
        defaultValue: a.string(),
        options: a.string().array(), // For future use with options of values
        dataEntries: a.hasMany("DataEntry", "dataCategoryId"),
        dataTypeId: a.id().required(), // ✅ Explicitly define the reference field
        dataType: a.belongsTo("DataType", "dataTypeId"),
        entryCount: a.integer().default(0),
      })
      .secondaryIndexes((index) => [index("name")])
      .authorization((allow) => [
        allow.owner(),
        allow.groups(["Admins"]).to(["read"]),
        allow.publicApiKey(), // TODO: Remove. FOR TESTING
      ]),
    DataEntry: a
      .model({
        note: a.string(),
        category: a.belongsTo("DataCategory", "dataCategoryId"),
        dataCategoryId: a.id().required(),
        date: a.date().required(),
        value: a.string().required(),
        dummy: a.integer().default(0),
      })
      .secondaryIndexes((index) => [
        index("dataCategoryId")
          .name("categoryEntriesByDate")
          .queryField("listCategoryEntries")
          .sortKeys(["date"]),
        index("dummy")
          .name("entriesByDate")
          .queryField("listByDate")
          .sortKeys(["date"]),
      ])
      // client.models.DataEntry.listDataentryByDataCategoryId({dataCategoryId: "ID"})
      .authorization((allow) => [
        allow.owner(),
        allow.groups(["Admins"]).to(["read"]),
        allow.publicApiKey(), // TODO: Remove. FOR TESTING
      ]),
  })
  .authorization((allow) => [allow.resource(postConfirmation)]);

export type Schema = ClientSchema<typeof schema>;

// export const schema = schema;
export { schema };

export const data = defineData({
  schema,
  authorizationModes: {
    defaultAuthorizationMode: "userPool", // Changed from public api key. https://docs.amplify.aws/react/build-a-backend/data/customize-authz/
    apiKeyAuthorizationMode: {
      expiresInDays: 30,
    },
  },
});

Attempts

Attempt 1

This time I tried partially custom types, still errored.

type ResolvedDataType = Omit<Schema["DataType"]["type"], "dataCategories"> & {
  dataCategories?: Schema["DataCategory"]["type"][];
};

type EnrichedDataCategory = Omit<Schema["DataCategory"]["type"], "dataType"> & {
  dataType?: ResolvedDataType;
};

export function subscribeToDataCategories(
  callback: (items: EnrichedDataCategory[]) => void
): () => void {

Attempt 2

Here I tried just adding DataType to the standard DataCategory type but it also errored.

export function subscribeToDataCategories(
  callback: (
    items: (Schema["DataCategory"]["type"] & {
      dataType?: Schema["DataType"]["type"];
    })[]
  ) => void
): () => void {

Resizing columns issue in AG Grid React

I have two grids which are in sync using alignedGrids property. I gave first two columns as flex:0 with minWidth and remaining n columns as flex:1 weith minWidth as 140.

When I resize the browser to small and back to large, first grid aligns fine but 2nd grid not aligning as expected, its stuck at minWidth at 140 and not flexing back to full width.

I’m looking for a solution in React

How to read from .Net Core FileStream in Javascript/Axios?

Endpoint:

[HttpGet("GetFileStream/{id}")]
[Produces("application/octet-stream")]
public async Task<Stream> GetFile(int id)
{
  Stream stream = await Services.FileStorage.GetFileStream(id, CurrentUserId);
  return stream;
}

 public async Task<Stream> GetFileStream(int id, string currentUserId)
 {
   FilePath filePath = await GetAsync(id);

   if (filePath == null)
   {
     return null;
   }

   if (File.Exists(filePath.fileName))
   {
     StreamContent stream = new StreamContent(File.Open(filePath.fileName, FileMode.Open));
     return await stream.ReadAsStreamAsync();
   }

   return null;

 }

The response contains the first chunk of bytes, but my pdf is blank of text and images don’t load correctly either.

const getFile = async (id, fileType) => {
  const url = Endpoints.fileStorage.getFile.replace("{id}", id);
  const response = await httpService.get(url, {
    responseType: 'application/octet-stream'
  });

  return response;
};

View code:

const renderFileContent = () => {
    if (!fileContent)
      return null;
    const { fileData, metaData, extension } = fileContent;
    if (filePathId) {
      //Stream file
      if (extension === "png" || extension === "jpg") {
        return (
          <div>
            <img src={`data:image/png;base64,${Buffer.from(fileData?.data, 'binary').toString('base64')}`} />
          </div>);
      }
      else if (extension === "pdf") {
        return (
          <div>
            <Document
              file={Buffer.from(fileData?.data, 'binary').buffer}
              onLoadSuccess={onDocumentLoadSuccess}>
              <Page pageNumber={pageNumber} />
            </Document>

            <p>
              Page {pageNumber} of {numPages}
            </p>
          </div>
        )
      }
    }

    else return null;
  };

With this code I get:
Warning: Invalid stream: “FormatError: Bad FCHECK in flate stream: 120, 253”

All of the Docs for streams in .net are for razer/blazor. Is there a way to parse in javascript?

I have tried many conversion methods, but I think the problem is I am not gathering all of the data from the stream. Because when I paste the bytes received into a base64 to pdf I get 12 blank pages as pdf.

I have also played around with returning different content-type headers, but none of them change the response, and ‘stream’ doesn’t work like nodejs.

I’m expecting to be able to constantly read from the endpoint or a reader but not sure what to return from my httpService function.

There is also this: https://github.com/dotnet/aspnetcore/pull/34817 but it’s unclear whether this will work using axios since there is a consumer? (I don’t know much about blazor)

How to scroll automatically to specific id when opening the url in react

Nav.jsx

<a href="#fee">Fee</a>
<a href="#proses">Proses rekber</a>

App.jsx

<section id="fee">
this is fee section
</section>
<section id="proses">
this is proses section
</section>

Problem :
when clicking the link for the first time didnt scroll down automatically and need to reload the page first to navigate to spesific id.

demo :

https://www.raijinshop.store/#fee

expected :
when click the link automatically scroll to spesific id section like this https://v5.reactrouter.com/web/api/Hooks/uselocation.

ES Modules JS not working in GCP functions

Below has the details , tried multiple updates, still no luck
works in VS code but not in gcp – cloud run
package.json


{
  "name": "whatsappendpoint-test2",
  "type" : "module",
  "engines": {
    "node": ">=14.0.0"
  },
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
   
  }
}

Code

export function test(req, res) {
    import {MY_CONST} from './consts.js';
    console.log(test)
    res.send('Hello world');
};

BUILD ERROR

Running "node --check index.js"enter code here
/workspace/index.js:4
import {MY_CONST} from './consts.js'
^
SyntaxError: Unexpected token '{'
at checkSyntax (node:internal/main/check_syntax:74:5)
Node.js v22.14.0