Alright so I’m trying to display all images in a particular directory through a express node app. On the client side I’m mapping the image as such
import './App.css';
import React, {useState, useEffect} from 'react';
//import logo from "./logo.svg"
function App() {
const [bdata, setBData]=useState([{}])
useEffect(()=>{
fetch("/api").then(
response=>response.json()
).then(
data =>{
setBData(data)
console.log(data)
}
)
},[])
return (
<div className="App">
{
(typeof bdata.dirFiles === 'undefined')?
(
<p>Loading</p>
):
(
bdata.dirFiles.map((file, i) =>(
(file.type=="Img")?(
<div key={i}>
<img src={require(file.url)}/>
<img src="./logo.svg"/>
<p>{file.url}</p>
<p>{file.name}</p>
</div>
):(
<div >
<p>{file.url}</p>
<p>{file.name}</p>
<p>{file.type}</p>
</div>
)
))
)
}
On the server side I’m Sending the data as such
app.get("/api",(req, res)=>{
//just the json is required here. Passing in an array of objects not viable
res.json(parseDirectories()[0])
})
function parseDirectories(){
let allFiles=[]
for (var i=0; i<directories.length;i++){
allFiles.push({"dirFiles":getFiles(path.resolve(directories[i]))})
}
return allFiles
}
function getFiles(dir){
const fileList =fs.readdirSync(dir)
let files=[]
for (const file of fileList) {
const name = `${dir}/${file}`
// Check if the current file/directory is a directory using fs.statSync
if (fs.statSync(name).isDirectory()) {
// If it is a directory, recursively call the getFiles function with the directory path and the files array
break
} else if (isImage(file)){
// If it is a file, push the full path to the files array
files.push(convertReadable(file,name))
}
}
return files
}
function convertReadable(file, name){
let readableFile={}
if(isImage(file)){
readableFile={"url": path.relative(appPosition, name),
"name": file,
"type":"Img"
}
}
return readableFile
}
function isImage(file){
let y=false
for (var i =0; i<Images.length; i++){
let ext=file.split(".").pop()
console.log(ext)
if(ext==Images[i]){
y=true
}
}
return y
}
The problem I’m running into is that
- the directory is outside the project folder (this is non negotiable and has to be there)
- react is not displaying pictures without import statements which makes it hard as the imports would then have to be dynamic.
Is there a library I could use for the purpose or maybe send the image file as a response. Unfortunately not sure of either. Just looking for help on this. Thanks in advance.