0

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?

Tyler N
  • 301
  • 2
  • 14

2 Answers2

0

To list the names of all the files within a folder try:

fs.readdir('path-to-your-folder', (error, files) => {
    if (error) {
        console.error(error);
        return;
    }
    files.forEach(file => {
        console.log(file);
    }) 
})
Ishan Joshi
  • 487
  • 3
  • 7
  • 1
    Calling this from a browser results in `fs is not defined` – Tyler N Sep 27 '19 at 18:38
  • `fs` is backend module. You cannot use it in the browser. You will have to make a server side application that serves these files to your frontend – Ishan Joshi Sep 27 '19 at 18:40
  • I see. I would have to, in a sense, 'push' the image on the server to the website, instead of 'pull' the image on the server from the website? – Tyler N Sep 27 '19 at 18:43
  • Yes, you would need to push the image from the server to the website – Ishan Joshi Sep 27 '19 at 18:44
  • ExpressJs is a pretty easy way to achieve this. – Ishan Joshi Sep 27 '19 at 18:45
  • If i'm not mistaken, I install Express through Node, and then when I run `npm start` it will run the JavaScript file that uses Express to push the images to the website? – Tyler N Sep 27 '19 at 18:53
  • Yes. This [Youtube video](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=8&cad=rja&uact=8&ved=2ahUKEwi51_Pd1vHkAhUGPI8KHfbRCeAQwqsBMAd6BAgKEAk&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpKd0Rpw7O48&usg=AOvVaw1nJqOb1rIwiGxvWYunZrYz) may help – Ishan Joshi Sep 27 '19 at 18:55
0

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!

Tyler N
  • 301
  • 2
  • 14