Skip to content

Node JS – Auto Generate a Photo Gallery from a Directory

Last updated on November 21, 2022

In my previous articles, I wrote a tutorial on this topic but it was in PHP, in this post I would like to show you, how you can generate a photo gallery based on the images within a given directory using Node js as a platform, and express js as a framework.

I am not going to write about express js or node js here, as that topics are out of scope for this tutorial, let’s focus on the topic directly, if you need more information on node js and express js please feel free to visit – https://nodejs.org/, https://expressjs.com/

This project is simple. We will use the express web server which does the task of routing and HTML generation with pug template engine.

{
  "name": "photo-gallery",
  "version": "1.0.0",
  "description": "Node js – Auto Generate a Photo Gallery from a Directory",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "arjun <arjunphp@gmail>",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.2",
    "pug": "^2.0.0-beta11"
  }
}

Installing dependencies

Save the above JSON string in the package.json file, and from that folder, open your terminal and type

npm install

With issuing the above command, the node package manager will pull all the required dependencies into node_modules folder under your project root folder.

Create a file called server.js, you can name it as you wish but make sure to update package.json file.

const fs = require('fs');
const express = require('express');
const app = express();
const path = require('path');

app.set('view engine', 'pug');
app.use('/static', express.static(path.join(__dirname, 'uploads')))

app.get('/get-images', (req, res) => {
    let images = getImagesFromDir(path.join(__dirname, 'uploads'));
     res.render('index', { title: 'Node js – Auto Generate a Photo Gallery from a Directory', images: images })
});

// dirPath: target image directory
function getImagesFromDir(dirPath) {

    // All iamges holder, defalut value is empty
    let allImages = [];

    // Iterator over the directory
    let files = fs.readdirSync(dirPath);

    // Iterator over the files and push jpg and png images to allImages array.
    for (file of files) {
        let fileLocation = path.join(dirPath, file);
        var stat = fs.statSync(fileLocation);
        if (stat && stat.isDirectory()) {
            getImagesFromDir(fileLocation); // process sub directories
        } else if (stat && stat.isFile() && ['.jpg', '.png'].indexOf(path.extname(fileLocation)) != -1) {
            allImages.push('static/'+file); // push all .jpf and .png files to all images 
        }
    }

    // return all images in array formate
    return allImages;
}

app.listen(8080, function () {
    console.log(`Application is running at : localhost:8080`);
});

Here is my view file, which uses the pug template engine.

html  
  head
    title= title
  body
  h1=title
    ul
    each image in images
        li 
            img(src=image width=300)

Running Project

Just issue the following command from the terminal, but before doing that please update the folder name and path from where you want to pull images.

 npm server.js 

Now head over to your browser and access http://localhost:8080/get-images, you will get output similar to the below,

4 1 vote
Article Rating
Subscribe
Notify of
guest

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments