Downloading multiple files from Google Cloud Storage in NodeJS

I am hosting a NodeJS app on Heroku in which users can upload their own images. I am hosting those images on Google Cloud Storage because Heroku will wipe them if they weren’t part of the deployment. So I check to see if the images are on the server. If they aren’t on the server, then they are requested from GCS.

When I try to download multiple images from a GCS Bucket to my host server, all image files downloaded will be the same as the last image in the request. If I have 1 image in the request, then the downloaded image will be correct. If I have more than one file, then only the last downloaded image is correct. The rest of the files have the correct filename, but the image downloaded for all of them are identical.

images.forEach((req) => {
  if (!fs.existsSync(`uploads/${req.imageName}`)) {
    storage.downloadImage(req.imageName).catch(console.error);                
  }
});

I have tried using async/await (awaiting the download) based on this post, but that yielded the same results. I’m not sure how to validate if a file on the server has completed a download.

how to generate a static function without ‘class{}’?

how do I generate something like:

function generator() {
static funct(){}
}

I think I’m wrong, but from what I understand the class {} method is built on top of function(){}, so it should have the same method. The point is that static methods don’t have a .prototype, and I’d like to know how they’re created via class {}

React: Can’t create li element because Promise();

I cannot figure out how to access this Promise object. How to map this promise? And why my async/await function is returning a promise and not a result object?
Any feedback appreciated.

Promise {<pending>}
 [[Prototype]]: Promise
 [[PromiseState]]: "fulfilled"
 [[PromiseResult]]: Array(2)
   0: "hey"
   1: "bye"
   length: 2[[Prototype]]: Array(0)
import { io } from "socket.io-client";
import { useState, useEffect } from "react";
function App() {
  const [text, setText] = useState("");
  const [socket, setSocket] = useState();
  const [chat, setChat] = useState([]);
  useEffect(() => {...}, []);
***//getting previous chat for new users.***

  useEffect(async () => {
    let mounted = true;
    const response = await fetch("http://localhost:4000/main_chat").then(
      (res) => {
        if (mounted) {
          setChat(res.json());
        }
      }
    );

    return () => (mounted = false);
  }, []);

  useEffect(() => {...},[socket]);

  const handleClick = () => {
    socket.emit("sentFromClient", text);
  };
  return (
    <div>
      <ul>{console.log(chat)}</ul>
      <input value={text} onChange={(e) => setText(e.target.value)}></input>
      <button onClick={() => handleClick()}>enter</button>
    </div>
  );
}

export default App;

Angular error ‘can’t read undefined properties in sax.js: 222’ [closed]

step to detail:
I installed the xml2js dependency in my angular project which already had several installed
dependencies like sax and i couldn’t do the app build so i installed some dependencies for angular to recognize xml2js like:
npm install timers-browserify
npm install stream-browserify
furthermore i modified the tsconfig.json
but now I do ng serve the project and I get the following error:

 Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
    at sax.js:222
    at Object../node_modules/xml2js/node_modules/sax/lib/sax.js (sax.js:1565)
    at __webpack_require__ (bootstrap:79)
    at Object.<anonymous> (parser.js:9)
    at Object../node_modules/xml2js/lib/parser.js (parser.js:381)
    at __webpack_require__ (bootstrap:79)
    at Object.<anonymous> (xml2js.js:12)
    at Object../node_modules/xml2js/lib/xml2js.js (xml2js.js:39)
    at __webpack_require__ (bootstrap:79)
    at Module../src/app/**/**/**/**.component.ts (main.js:5014)
    ```

I am writing a function to modify the objects inside. 1 problem: One of the object properties is not the last element, seems like it needs to array?

const recordCollection = {
    2548: {
      albumTitle: 'Slippery When Wet',
      artist: 'Bon Jovi',
      tracks: ['Let It Rock', 'You Give Love a Bad Name']
    },
    2468: {
      albumTitle: '1999',
      artist: 'Prince',
      tracks: ['1999', 'Little Red Corvette']
    },
    1245: {
      artist: 'Robert Palmer',
      tracks: []
    },
    5439: {
      albumTitle: 'ABBA Gold'
    }
  };
  
  **// Only change code below this line**

  function updateRecords(records, id, prop, value) {
     **2548 Jon Bon Jovi** 
        if (value === "") { 
        delete records[id].artist;
        delete records[id].tracks;
    } 

      **//5439 ABBA**
    else if (prop === 'tracks') {
        recordCollection[id].tracks = [];
        records[id].tracks.push(value);

This is the error iMessage I am getting in regards to the ABBA song:
After updateRecords(recordCollection, 5439, “tracks”, “Take a Chance on Me”), tracks should have the string Take a Chance on Me as the last element.I Think they want me to Create an Array? But I thought the Abba song was the last element

       **// 5439 ABBA**
    } else if (prop === "artist") {
        records[id].artist = value;

      **// 1245 Robert Palmer**
    } else if (prop === "tracks") {
        records[id].tracks.push(value);
      
      **// 1245 Robert Palmer**
    } else if (prop != "tracks") {
        records[id].albumTitle = "Riptide";

    }
    
    
    return records;
  }

How to edit several audio clips into a larger audio clip for download in one audio file (HTML, JS)?

How can I mix several audio clips together in order to make one assembled audio file for download. Like audio Mad Libs. Remember Mad Libs?

Here’s what I’ve got so far (it’s not much):

var audio = document.getElementById('mad-libs')
var audio1 = document.getElementById('1')
var audio2 = document.getElementById('2')
var audio3 = document.getElementById('3')
var audio4 = document.getElementById('4')
var audio5 = document.getElementById('5')
var audio6 = document.getElementById('6')
var record = document.getElementById('record')
var mediaRecorder = null
var recording = false
var chunks = []

recordAndStore(audio1)

function recordAndStore (slot) {
  navigator.mediaDevices.getUserMedia({
    audio:true
  }).then(function (stream) {
    mediaRecorder = new MediaRecorder(stream)
    record.addEventListener('click', function (event) {
      if (recording == false) {
        recording = true
        mediaRecorder.start()
        record.textContent = '⏹️ Stop'
      } else {
        recording = false
        mediaRecorder.stop()
        record.textContent = '⏺️ Record'
      }
      mediaRecorder.ondataavailable = function (data) {
        var audioURL = window.URL.createObjectURL(data.data)
        slot.src = audioURL
      }
    })
  }).catch(function (error) {
    console.log(error)
  })
}
audio.hidden {
  display: none;
}
button {
  font-size: 1.35em;
  padding: .25em .5em;
  cursor: pointer;
}
<h1>Mad Libs</h1>
<p>Get Ready To Record Your Mad Libs</p>
<p>Click the record button and say a "noun," "verb," "adjective," or anything else you're prompted for »</p>
<h4 id='prompt'>Common Noun</h4>
<button id="record">⏺️ Record</button>
<audio id="mad-libs" src='audios/mad-libs.m4a' controls class='hidden'></audio>
<audio id='1' controls></audio>
<audio id='2' controls></audio>
<audio id='3' class='hidden'></audio>
<audio id='4' class='hidden'></audio>
<audio id='5' class='hidden'></audio>
<audio id='6' class='hidden'></audio>
<button id="download">Download</button>

<!--

This is the mad libs story...

Once upon a time there was a king with a great big
______ (common noun).

And every morning he took it out on the royal balcony
and ______ (verb, past tense) it for at least 3 hours.

This exhausted the king, and he was very ______
(adjective) to begin with.

The people had gotten very ______ (adjective) with the
king's morning routine.

So they gathered all their ______ (noun, plural),
stormed the castle and ______ (verb, pased tense) the
king.

THE END


-->

I’d like the user to be able to record their prompts (noun, verb, adjective, etc), and then play them back in the context of the mad libs story (which is recorded ahead of time for them in an animated voice).

Plus! Importantly, I want to let them download their creation with a download button.

I’ve gotten lost in Array Buffers and Blobs, and I can’t make much sense of how to do this. Am I better off trying to use WASM with ffmpeg? Or Media Recorder API? Help would be awesome : )

Project help: $ is not defined (JavaScript) (Replit IDE) [duplicate]

I am currently using the online version of the Replit IDE (I don’t know if being online is a problem). In my project, I have this block of code; however when I run it, it states that $ is not defined. I ask if this is a problem related to how I use run the different files, as all I do is declare ‘node public/main.js’ rather than several different files. If anyone has experience Replit, it would be appreciated if you could guide me through the IDE. Thank you in advance 🙂 (sorry if I reply slowly).

Here is the block of code I’m having trouble with:

// Page Elements
const $input = $('#city');
const $submit = $('#button');
const $destination = $('#destination');
const $container = $('.container');
const $venueDivs = [$("#venue1"), $("#venue2"), $("#venue3"), $("#venue4")];
const $weatherDiv = $("#weather1");

How to remove duplicates from an array object in javascript

I want to remove duplicates, and to left only unique items in a sub-object array.

function display_message() {
  let filteredSerivces = 
  [
    {
        "ServiceTypeId": 805,
        "ServiceTypeName": "Custom Services 1",
        "GroupedServices": [
            {
                "Id": 5247,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A2",
                "Name": "A1",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3683
            },
            {
                "Id": 5254,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A2",
                "Name": "A2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3683
            },
            {
                "Id": 5254,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A6",
                "Name": "A2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3684
            }
        ],
        "Order": 4
    },
    {
        "ServiceTypeId": 804,
        "ServiceTypeName": "Custom Services 2",
        "GroupedServices": [
            {
                "Id": 5246,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B1",
                "Name": "B1",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3696
            },
            {
                "Id": 5248,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B2",
                "Name": "B2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3700
            },
        {
                "Id": 5248,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B2",
                "Name": "B2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3683
            }
        ],
        "Order": 5
    }
]


//TASK: The goal is to remove duplicate object (leave just one) from an array object GroupedServices
// the key for this distinction is "Id".
// example: 
//            {
//                "Id": 5254,
//                "ServiceTypeId": 805,
//                "ServiceName": "Some service A2",
//                "Name": "A2",
//                "Duration": 30,
//                "DurationForClient": 30,
//                "Order": 4,
//                "EmployeeId": 3683
//            },
//            {
//                "Id": 5254,
//                "ServiceTypeId": 805,
//                "ServiceName": "Some service A6",
//                "Name": "A2",
//                "Duration": 30,
//                "DurationForClient": 30,
//                "Order": 4,
//                "EmployeeId": 3684
//           }
//=> in this case we need to remove second object, because it has same Id with a first object (Id: 5254) 

//WHAT I HAVE BEEN TRIED:
var uniqueGroupedServices = Array.from(filteredSerivces.GroupedServices().reduce((map, obj) => map.set(obj.Id, obj), new Map()).values());



    
    
  console.log(uniqueGroupedServices);

}
<input type="button" onclick="display_message();" value="click"/>

But obviously my code doesn’t work. I guess I need to iterate for each in this main array to approach to GroupedServices but I don’t know how. Also, how can I remove second occasion of same object (same Id)?

Error package vscode extension with vsce: invalid relative path

  • npm: 8.1.0
  • vsce: 2.5.3

I have a npm package (colibri) in a local folder and a VSCode extension (vscode-teroshdl) in other folder. colibri is a dependency of vscode-teroshdl:

    "dependencies": {
        "colibri": "file:../colibri"
    },

When I try to package the VSCode extension:

cd colibri
npm install
cd ../vscode-terosHDL
npm install
vsce package

It fails with the error:

 ERROR  invalid relative path: extension/../colibri/node_modules/cli-progress/CHANGES.md

String parameter passed in javascript does not work

Just trying to understand whats going on here. Obviously a quirk of javascript, hoping someone can help explain.

HTML:

<input type="file" asp-for="TitleImageUrl" value="@_loc[Model.AddTitleImageButton]" onchange="preview('CardDynamicImage')" />

<img class="card-img-top embed-responsive-item" id="CardDynamicImage" src="@Model.CardTitleImage" onerror="this.src=''">

JAVASCRIPT THAT WORKS:

function preview(elementId) {
<!--The id of the element is hard coded directly. Ignore the value passed in.-->
            CardDynamicImage.src = URL.createObjectURL(event.target.files[0]);
    }
}

JAVASCRIPT THAT DOES NOT WORK: Why?

function preview(elementId) {
<!--Trying to pass in the id of the element does not work.-->
            elementId.src = URL.createObjectURL(event.target.files[0]);
}

fixed side scrollbar for case study

This is my first post. I am new to code and am trying to code my case studies for my portfolio. I want to include a “scroll bar” to work as a sort of timeline on the left side that is “fixed” so as you scroll down the page it fills up. This website has a something close to what I am looking to accomplish. they have a small red “scroll bar” on the left side.

https://edesigninteractive.com/

Vanilla js class factory

I was trying to implement some kind of factory that create a class definition in the run time,I figure this work my code look like this


 function JsClassFactory() {
    this.X = class {

    };
    this.addMethod = (name, def) => {
        let Y = class extends this.X {
            constructor() {
                super()
                this[name] = def
            }
        }
        this.X = Y
        return this;
    }

    this.addAttribute = (name, def) => {
        this.addMethod(name, def)
    }

    this.getClass = function () {
        return this.X
    };
}


(function () {
    const cf = new JsClassFactory()
    cf.addAttribute('age', 35)
    cf.addAttribute('name', 'chehimi')

    cf.addMethod('myName', function () {
        console.log(' i am %s', this.name)
    })
    cf.addMethod('myAge', function () {
        console.log('my age is', this.age)
    })
    let z = new (cf.getClass())
    z.myName();
    z.myAge()
    cf.addAttribute('name', 'ali')
    cf.addAttribute('age', 15)
    let t = new (cf.getClass())
    t.myName();
    t.myAge()
})()

i am asking if there is a better a way to implement this feature?
or a better work arround,