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?

11
  • 1
    Don't ask two things/topics in one question. Commented Sep 6, 2021 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. Otherwise you'll need ajax to load that JSON. Commented Sep 6, 2021 at 12:30
  • 1
    @ChrisG you miss that the result of fs.readdir is async. Commented Sep 6, 2021 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. Commented Sep 6, 2021 at 12:33
  • 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: github.com/khrismuc/express-images Commented Sep 6, 2021 at 12:59

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.