Vhin Gabuat
Vhin Gabuat

Reputation: 13

Reading Files Asynchronously and Displaying them on the page

Hello I am trying to display images from a folder in my project using the "fs" module with NodeJS, I need to read all images in a directory and run them in a loop for them to be displayed I was able to do it but I'm not sure if this is the proper or good way to do it. Thanks in advance for your help.

I inserted my readdir (Reading Files Asynchronously) inside my Homepage route.

const express = require('express');
const router = express.Router();
const fs = require('fs');

router.get('/', function(){ 
    fs.readdir('./assets/images/', (err, files) => {
        if(err) {
            throw err;
        }
        res.render('home', {
            files: files
        });
    });
});

module.exports = _router;

The images were displayed but I have no one to ask if I did it the proper way. Please help, thank you!

Upvotes: 0

Views: 40

Answers (1)

jfriend00
jfriend00

Reputation: 707158

If what your template is expecting is an array of filenames and that's what you're trying to render with that template and you want to read the list of files from the directory on every request without any caching, then this is the way to do it.

A few issues to clean up:

  1. You do need some proper error handling. if (err) throw err is not proper error handling. You need to send a response to the request, probably a 500 response status and probably want to log the error.

  2. It also looks like you aren't exporting the same variable for the router you created. You are creating router, but exporting _router

Cleaned up code:

const router = require('express').Router();
const fs = require('fs');

router.get('/', function(){ 
    fs.readdir('./assets/images/', (err, files) => {
        if(err) {
            console.log("fs.readdir error: ", err);
            res.sendStatus(500);
        } else {
            res.render('home', {files});
        }
    });
});

module.exports = router;

Upvotes: 1

Related Questions