display files on page using express response

Is there a way to transfer files from the server for display in the browser within the index pug file?

   extends layout block content h1= 'saved files' #recordings.recordings.row script(src='/javascripts/listrecordings.js')
    function fetchRecordings() {
      fetch('/')
        .then((response) => response.json())
        .then((response) => {
          console.log("response " + response);
          if (response.success && response.files) {
            //remove all previous recordings shown
            recordingsContainer.innerHTML = '';
            response.files.forEach((file) => {
              //create the recording element
              const recordingElement = createRecordingElement(file);
              //add it the the recordings container
              recordingsContainer.appendChild(recordingElement);
            })
          }
        })
        .catch((err) => console.error(err));
    };

Here is the relevant part of the index js:

    router.get('/', (req, res) => {
      let files = fs.readdirSync('./public/upploads');
      console.log(__dirname + " files length  " + files.length);
      files = files.filter((file) => {
        // check that the files are audio files
        const fileNameArr = file.split('.');
        return fileNameArr[fileNameArr.length - 1] === 'mp3';
      }).map((file) => `/${file}`);
      //res.json({ success: true, files });
      res.render('index', files);// stuck here ???

    });

Can anyone help with sending a response to the index in this scenario?

Answer №1

One efficient approach could be to retrieve an array containing the paths to the .mp3 files, like this:

['resources/a.mp3', 'resources/b.mp3']

In the client-side code, all that's required is to load the audio using the corresponding URL:

http://example.com/resources/a.mp3

To configure your public directory properly, refer to the guidelines provided in this documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

The script is not functioning properly when placed outside of the HTML body tag

I have a main template that is functioning properly with the layout I've included here. However, I am facing an issue when trying to organize the scripts within one block. Specifically, when I move one of the scripts from the body section to the head ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

The node.js API request is experiencing a unresponsive state

As a newcomer to the world of JavaScript, I am currently learning the basics of Node.js. One task I'm working on involves retrieving a contact from my mongoDB and creating a GET method to return it. Sounds simple, right? Below is the router method I ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

Why does one HTML link function while the other does not?

After creating links that connect two HTML files, I encountered an issue where one link does not work. The situation involves a folder named aiGame containing the aiindex.html file along with ai.js and ai.css. It is worth noting that the index.html file is ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Utilizing the JavaScript map method to structure API response data

Here is the JSON data I have: { "result": [{ "name": "a", "value": 20, "max": 100, "sale_value": [{ "no": 1, "name": "aaaaa", "price": 200 }, { "no": 2, ...

The req.body variable is not defined in this context, which means only the default MongoDB id is

I've been attempting to utilize a post request for inserting data into MongoDB using Mongoose, but I keep encountering an issue where req.body is undefined. The document gets inserted into the database, but only the default Object ID is included. Thi ...

Determining the precise mouse location within child elements regardless of zoom level, scrolling, or dimension changes

My goal is to accurately determine mouse coordinates within the page elements. To see the code in action, please visit: http://jsfiddle.net/t8w9k6gu/ $('#p1, #p2, #p3').on('click mousemove touchmove', function(ev){ var target = ...

Is there a way to ensure my React navigation screen fills the entire screen?

I am currently facing an issue where my map screen is not covering the whole screen, leaving a blank space at the bottom where the custom bottom navigator should be displayed. How can I adjust my code so that the map covers this blank space at the bottom? ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

What could be the reason for the malfunctioning of jquery hover functionality?

My goal is to develop a unique text editor that can send Ajax requests when a word is hovered. The code snippet below shows my progress so far: <div class="word_split" contenteditable="true">Don't break my heart.</div> Included in the pa ...

Knex - Querying multiple tables with sorting capabilities

Can you help me with translating this code snippet to knex.js? SELECT id, Sum(x.kills) AS total FROM (SELECT id, kills FROM bedwars_player_solo UNION ALL SELECT id, kills FR ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

Mock needed assistance

In my testing scenario, I am attempting to simulate a service that is utilized by my function using sinon. However, I am encountering difficulties in inserting the mock into my function. The service is obtained through the use of require The structure of ...

Discovering an item using two different text inputs

I am attempting to retrieve the HTML element object that contains two specific strings. Below is an example with two divs, each named case. I want to access the object based on the content of the p tags inside them: <div class="case"> <p> ...

How can I prevent buttons from interfering with an onPaste event?

I've created an image modal that allows users to upload or paste an image. Everything is working well, except for the fact that the buttons on the modal are capturing the focus. This means that pasting only works if the user manually clicks outside th ...

How can websockets be utilized to refresh information from worker servers?

I am managing a server with expressjs that serves as the admin website, along with 4 to 10 worker servers dedicated to running a job scheduler and handling incoming data processing. I am looking for efficient methods for the worker servers to communicate ...

Starting up an express server with mocha testing

My express server throws an error when certain parameters are missing, such as the DB URI. I want to use Mocha to test this behavior, but I am not sure how to go about it. if(!parameters.db) { throw new Error('Please provide a db URI'); } I ...