3
\$\begingroup\$

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.

I inserted my readdir (Reading Files Asynchronously) inside my Homepage route. The images were displayed but I have no one to ask if I did it the proper way.

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;

\$\endgroup\$
2
  • \$\begingroup\$ Perhaps you should also provide us the res.render function \$\endgroup\$
    – konijn
    Commented Jul 22, 2019 at 11:57
  • \$\begingroup\$ Hi @konijn, res.render function is from express module required on top, you can check here for reference --> expressjs.com/en/api.html#res.render . Thank you! \$\endgroup\$ Commented Jul 22, 2019 at 22:44

2 Answers 2

5
\$\begingroup\$
  • Don't use callbacks, it's hard to read and maintain, the fs.readdir function will return a promise if you didn't provide a callback function.
  • Use arrow functions when you could.
  • Respond with an error instead of throwing (unless you have a catch wrapper middleware).
  • Use property shorthands.
  • You forgot req and res.

Try this:

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

router.get('/', async (req, res) => { 
  try {
    const files = await fs.readdir('./assets/images/')
    res.render({ files })  // notice the property shorthand
  } catch (error) {
    res.status(404).json({ error })
  }
});

module.exports = router;

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is cool! Thanks Man very much appreciated! \$\endgroup\$ Commented Aug 30, 2019 at 1:40
1
\$\begingroup\$

That's not a lot to review, but it looks textbook good.

If anything, the value of './assets/images/' could have been an upfront declared constant, or could have been retrieved from a configuration file.

\$\endgroup\$
1
  • \$\begingroup\$ @konjin Thanks for making time reviewing my code, Your advice is highly appreciated! Thanks again! \$\endgroup\$ Commented Jul 22, 2019 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.