Node.js 如何在express环境中从images目录中获取随机图像
我想从images目录中随机获取一个图像。但是,我当前的代码不起作用。感谢您的帮助Node.js 如何在express环境中从images目录中获取随机图像,node.js,express,Node.js,Express,我想从images目录中随机获取一个图像。但是,我当前的代码不起作用。感谢您的帮助 var express = require('express'); var router = express.Router(); const fs = require('fs'); function getRandFile() { const imageDir = '../public/images/'; fs.readdir(imageDir, (err, files) => { files
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()
/
/公开的
/图像
|1.jpg
|2.jpg
|等
/路线
|index.js与require
函数不同,fs.readdir
(以及所有fs
函数)相对于当前工作目录工作,而不一定是当前脚本所在的目录。当前工作目录的位置取决于节点进程的启动方式
如果要访问相对于当前目录的文件,可以使用内置的\uuu dirname
全局,它始终包含当前执行文件的路径
var path = require('path')
const imageDir = path.resolve(__dirname, '../public/images/')