Ron I Ron I - 5 months ago 31
Node.js Question

How to get a random image from the images directory in an express environment

I wanted to randomly get an image from the images directory. However, my current code is not working. Any help is appreciated!

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

function getRandFile() {
const imageDir = '../public/images/';
fs.readdir(imageDir, (err, files) => {
files.forEach(file => {
//will add file name to an array and then return a random file name


/* GET home page. */
router.get('/', function(req, res, next) {
res.render('./index.jade', { backgroundImage:getRandFile() });

module.exports = router;

The error I get is:

files.forEach(file => {

TypeError: Cannot read property 'forEach' of undefined
at fs.readdir (/Users/ron/Dropbox/dev/moments/routes/index.js:9:8)
at FSReqWrap.oncomplete (fs.js:111:15)

The directory structure is:

| 1.jpg
| 2.jpg
| etc
| index.js <-- where I am calling the function getRandFile()


Unlike the require function, fs.readdir (and all fs functions) works relative to the current working directory, not necessarily directory the current script is in. Where the current working directory is depends on how the Node process was started.

If you want access files relative to the current directory, you can use the built-in __dirname global instead, which always contains the path to the currently-executing file.

var path = require('path')

const imageDir = path.resolve(__dirname, '../public/images/')