如何在快速的环境中从图像目录中获得一个随机的图像

我想随机从图像目录中获取图像。 但是,我目前的代码不起作用。 任何帮助表示赞赏!

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; 

我得到的错误是:

 /Users/ron/Dropbox/dev/moments/routes/index.js:9 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) 

目录结构是:

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

require函数不同, fs.readdir (和所有fs函数)相对于当前工作目录工作 ,不一定是当前脚本所在的目录。当前工作目录取决于Node进程的启动方式。

如果要访问与当前目录相关的文件,则可以使用内置的__dirname全局文件,而该文件始终包含当前正在执行的文件的path。

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