Express/Node - showing images from a directory

Is it possible to show every image in a directory in a template without explicitly naming the path of each file? Just iterating through them all somehow?

The simple answer is “Yes you can”. The longer answer is not one I could do off the top of my head, but it’s definitely doable. Are you using a database, and what are you using for a front end?

The frontend is modern vanilla js. I’m using handlebars for templating on the server. I’m not using a database because its not structured data that i need to sort through, its just a directory of images i want to dump onto the page.

You could use the readdir method from the fs module to loop over the images and add their paths to an array, then pass that into your handlebars template and use the {{#each}} helper to iterate over the array.

2 Likes

Thanks fretburner. That sounds like a good solution. I tried this:

app.get('/gallery', (req, res) => {

fs.readdir('./imgs', (error, files) => {
    var imgFiles = [];
    files.forEach(file => {
            var imgpath = __dirname + '/imgs/' + file;
            imgFiles.push(imgpath);
   
    })
   
    res.render('gallery.hbs', {imgFiles: imgFiles});   

})
});

The images are all 404ing. Paths all look something like this: /Users/owo3732/rand/nodething/imgs/bikeshedding.png

and… what should they be looking like? (We dont know your directory structure…)

@m_hutley fair point! I needed to put the imgs directory into the public folder and remove __dirname.

var imgpath = '/imgs/' + file;

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.