For this purpose, my approach is to read all image file names from a directory and pass that as an array to the front-end javascript, which then reads one-by-one to create a dynamic image elements.
Step 1: node
const path = require('path');
const fs = require('fs');
//joining path of directory
const directoryPath = path.join(__dirname, 'img');
const fileArray = [];
app.get('/', function(req, res) {
//passsing directoryPath and callback function
fs.readdir(directoryPath, function(err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function(file) {
console.log(file);
fileArray.push(file);
});
});
res.status(200).json({
data: fileArray push // not sure, is this the way?
})
});
var server = app.listen(3000, function() {});
Step 2: hence my front-end will look something like, where I need to loop over the recieved image files array.
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>
<div id="placehere">
</div>
</body>
</html>
question so how do I use the recieved array to form a dynamic img array in front-end?