Search code examples
javascriptnode.jsexpressbrowserpug

How to use Node.js File System to set the src of an img tag in a browser?


I am creating an html file meant to be viewed in a browser, and on the page there is a slideshow of images that plays. I would like the iterations of pictures to play through all pictures that are in a subfolder.

Optimally, I should be able to add/remove pictures from the images folder without touching the code or ever hardcoding the names of the files. I am trying to use node.js and require('fs') to return a list of available files from the folder, but I am completely new to node and have no idea how to call the node file from the browser. currently this is what I have:

website.html

<script src="app.js"></script>

app.js

const fs = require('fs');

const files = fs.readdir('./images', function(err, files) {
    if (err) console.log('Error: ', err);
    else console.log(files);
})

Running this in the browser throws the error require is not defined.

I have run npm install -g browserify in command prompt against the folder.

How can I implement my node file in such a way that the browser can access the files in the images folder?


Solution

  • If you already know how to set up your back-end server, here's the setup using Node, Express and Pug

    Node: server.js

    const express = require('express');
    const app = express();
    app.set('view engine', 'pug');
    
    app.use(express.static(__dirname + '/public'));
    
    const imagesFolder = './public/images/splash';
    const fs = require('fs');
    
    var filesArr = [];
    
    fs.readdir(imagesFolder, (err, files) => {
      files.forEach(file => {
        filesArr.push(file);
      });
    });
    
    app.get('/', (req, res) => {
      console.log(filesArr);
      res.render('splash', {
        filesArr : JSON.stringify(filesArr)
      });
    });
    

    Pug: splash.pug

    doctype html
    html
      body(style='overflow:hidden')
        div#theShow(style="height:100%; width:100%; background-repeat:no-repeat; background-position:center;")
        script.
          const files = JSON.parse('!{filesArr}');
        script(src='javascript/splashScreen.js')
    

    JavaScript: splashScreen.js

    var slideIndex = 0;
    showSlides();
    
    function showSlides(){
    
        var slideshow = document.getElementById('theShow');             
        slideshow.style.backgroundImage = "url('../images/splash/" + files[slideIndex] + "')";
    
        document.body.removeChild(slideshow);
        document.body.appendChild(slideshow);
    
        if (slideIndex < files.length) {
            slideIndex++;
        } else {
            slideIndex = 0;
        }
        setTimeout(showSlides, 6000);
    }
    

    With Node the readdir() funciton is used to read the directory, and the filesArr variable is given to the Pug file on the get request of the \, a.k.a. the root.

    Pug can then access the filesArr variable using !{}. The variable files is set to equal filesArr within its own script. and then the external script is called and has access to files

    It also worked out better for my use to change the backgroundImage of a div rather than the src of an img. But the javascript inside splashScreen.js could be easily rewritten to slideshow.src = "url('../images/splash/" + files[slideIndex] + "')"; where slideshow is an img element instead of a div.


    If, like me you're trying to do this before understanding how to set up a back-end server for your website

    There are multiple great resources on the internet about using Node, but sometimes they can be hard to find. It's even harder to find resources about how to get started for an absolute beginner.

    This YouTube video is very informative without too much fluff and shows how to get started from nothing. (The hyperlink timestamp starts at 9:20 which is when the actual programming begins, but the first part of the video is informative as well)

    After that video, the same YouTuber has a playlist where he makes a wesbite using Node, Express and Pug which you can watch to understand how to set up your back-end server and then you can utilize the code at the top portion of this answer!