Is there a way to retrieve the list of files from a static public folder using javascript?

I have successfully set up a public folder directory using express and node.

For instance, this code works perfectly -

var testImage = new Image();

testImage.src = '/images/png/avatar.png';

However, I need to access several images stored inside the png folder.

Is there a way for me to achieve something like this?

var imageFolder = new Folder();
var imageList = [];
imageFolder.src = '/images/png';

for(var image in imageFolder){
    imageList.push(imageFolder[image])
}

Answer №1

To access the contents of a directory, you can utilize fs.readdir. Here is an example:

Asynchronous method (recommended):

var fs = require('fs')
fs.readdir('/photos', function (err, files) {
  if (err) {
    return console.error(err)
  }
  
  var fileList = []
  files.forEach(function (file) {
    var fileObject = new File()
    fileObject.path = '/photos/' + file
    fileList.push(fileObject)
  })
})

Synchronous method:

var fs = require('fs')
var files = fs.readdirSync('/photos')
var fileList = []

files.forEach(function (file) {
  var fileObject = new File()
  fileObject.path = '/photos/' + file
  fileList.push(fileObject)
})

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

Upgrading Table Models with ASP.NET MVC 3 and Ajax

Trying to update a record list using ajax, displayed in a table where each record has a JavaScript delete link. When I load the table initially, the RemoveLink functions correctly. However, once the div "RecordListPartialView" is updated via ajax, it stops ...

What steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: 'use strict'; var Comment = require('../../../models/comment'); module.exports = { description: 'Create a Comment', notes: 'Create a comment&apos ...

The status of req.body in Express.js fluctuates unpredictably between being undefined

Having an issue where sometimes the req.body is undefined, but then running it again minutes later shows data. Your assistance is greatly appreciated index.js const http = require('http'); const express = require('express'); const bod ...

Adjusting the styling of a webpage in real-time

Here is the CSS code I am working with: .myTabs .JustForFun .ajax__tab_inner:hover { width: 109px; background: url ("/images/csc_tr.png") no-repeat 100% 0%; margin-right: 2px; background-color: #BBC614; } I want to change the background-c ...

Using Vue.js to submit a form in Laravel and redirecting with a flash message

I am facing an issue where I have two components named Index and Create, loaded from separate blade files. The challenge is passing a flash message as a prop between these components due to their file separation. How can I redirect after submitting a form ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

What is the best way to create dynamic queries in Sequelize using Node.js?

Looking for a Query Function that allows dynamic data retrieval with FindAll Query For instance, if I need to fetch data like age>5, I want to be able to do so using query parameters directly This is just an illustration In essence, I require a query ...

When the jQuery keyup event is triggered, the "function" will be incremented to 0

There are three input fields to search a JSON tree. When all three fields are filled correctly, the data from the next level of the JSON tree is retrieved. A number is incremented through the keyup event to access the next data of the JSON tree. However, ...

What is the best way to incorporate markers into my d3 line chart that includes two separate datasets?

In my JavaScript code, I'm creating a line chart for two datasets using the d3 library with Vue framework integration. Within the HTML code, there are buttons that trigger the updateData function to display the line charts for the respective datasets ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

Using hooks is restricted to the confines of a function component. An error will occur if they are called outside of this scope: "

How can I integrate a shopping cart feature into my app? I've created a separate file with the necessary functions, but I keep encountering an error related to invalid hook calls. export function CartProvider(props) { const [items, setItems] = u ...

What is the best way to calculate checksum and convert it to a 64-bit value using Javascript for handling extremely large files to avoid RAM overflow?

Question: What is the best method for generating a unique and consistent checksum across all browsers? Additionally, how can a SHA256/MD5 checksum string be converted to 64-bit? How can files be read without requiring excessive amounts of RAM when ...

Display message in a modal using React or JavaScript

Here's a puzzling query I have: Users can upload .MSG files to our system, and the BASE64 data is stored in the database. Now, I'm trying to incorporate these .MSG files into a model but facing conversion issues with BASE64 data. Interestingly, I ...

Display the initial JSON data object without the need to choose a link with the help of AngularJS

I have successfully built a webpage that displays JSON data based on the selected link. However, I am facing an issue where I need to show the first JSON data object before selecting any link (initially). Check out the Plunker demo here: http://embed.plnk ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

Getting the json array value and populating it in a dropdown list in angularjs - a step-by-step guide!

{"id":1,"firstName":"John1","lastName":"Doe1","**accountIds**":[12345,12346,12347],"recipients":[{"accountNumber":22222,"firstName":"Mary1","lastName":"Jane1"},{"accountNumber":33333,"firstName":"Mary2","lastName":"Jane2"}]} Show the "accountIds" as a dro ...

Is it possible to simultaneously wait for the completion of two methods instead of awaiting each one individually?

When dealing with 2 async methods, one may want to run them simultaneously but wait for both to finish before proceeding. Here is an example: exports.get = async id => { const part1 = await context.get(id); const part2 = await context.get2(id ...