1

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?

x-code
  • 608
  • 1
  • 10
  • 30
  • 1
    Don't ask two things/topics in one question. – t.niese Sep 06 '21 at 12:28
  • 1
    Just `res.status(200).json(fileArray)` is enough. However, "passing that to the fronend" is a little more complex. If your express app also serves the above frontend, you can easily put that image loop into a [view template](https://expressjs.com/en/guide/using-template-engines.html). Otherwise you'll need ajax to load that JSON. –  Sep 06 '21 at 12:30
  • 1
    @ChrisG you miss that the result of `fs.readdir` is async. – t.niese Sep 06 '21 at 12:31
  • 1
    Those are still two topics. The first part is the node code which does not work for you. And the second part is how to get it into your HTML which is a different topic. – t.niese Sep 06 '21 at 12:33
  • @t.niese Right, but OP can just use the Sync version instead. –  Sep 06 '21 at 12:33
  • Why not just `.json(files)`? Why iterate `files`, push every element in a new array, and send the new array? That's just sending `files` with extra steps – Jeremy Thille Sep 06 '21 at 12:34
  • thanks guys. so how would I use the incoming array to form the dynamic array – x-code Sep 06 '21 at 12:35
  • https://stackoverflow.com/questions/36310296/looping-through-images-array-and-showing-them-to-html-page – Jeremy Thille Sep 06 '21 at 12:37
  • @JeremyThille actually Im newbie, don't know how to get the array/files accessible in my index.html page so I can loop over them and create & append to my
    – x-code Sep 06 '21 at 12:47
  • Got it, I have posted a basic solution – Jeremy Thille Sep 06 '21 at 12:56
  • 1
    Since this comes up again and again (and people don't use view engines at all or the abysmal ejs) I've created a repo showing how to show these images server-side and using ajax: https://github.com/khrismuc/express-images –  Sep 06 '21 at 12:59

1 Answers1

1

A simple and classic approach would be something like this :

Back-end :

import { promises } from "fs";

app.get('/', async (req, res) => {
    try {
        const files = await promises.readdir(directoryPath);
        res.status(200).json(files);
    } catch (err) {
        res.status(500).json(err);
    }
});

Front-end :

let files;
try{
    const response = await fetch("/");
    files = await response.json();
    // files is now an array of file names, do what you want with that (create <img> tags, etc.)
} catch(err){
    console.error(err)
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63