【发布时间】:2021-09-06 20:56:29
【问题描述】:
为此,我的方法是从一个目录中读取所有图像文件名 并将其作为数组传递给前端 javascript,然后逐一读取 创建动态图像元素。
第 1 步:节点
const path = require('path');
const fs = require('fs');
//joining path of directory
const directoryPath = path.join(__dirname, 'img');
const fileArray = [];
app.get('/', function(req, res) {
//passsing directoryPath and callback function
fs.readdir(directoryPath, function(err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function(file) {
console.log(file);
fileArray.push(file);
});
});
res.status(200).json({
data: fileArray push // not sure, is this the way?
})
});
var server = app.listen(3000, function() {});
第 2 步: 因此我的前端看起来像,我需要循环接收的图像文件数组。
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>
<div id="placehere">
</div>
</body>
</html>
问题那么如何在前端使用接收到的数组来形成动态的img数组呢?
【问题讨论】:
-
不要在一个问题中问两个问题/主题。
-
res.status(200).json(fileArray)就足够了。但是,“将其传递给前端”要复杂一些。如果您的 express 应用也服务于上述前端,您可以轻松地将该图像循环放入 view template。否则,您将需要 ajax 来加载该 JSON。 -
@ChrisG 你错过了
fs.readdir的结果是异步的。 -
这仍然是两个主题。第一部分是不适合您的节点代码。第二部分是如何将它放入您的 HTML 中,这是一个不同的主题。
-
由于这种情况一次又一次地出现(而且人们根本不使用视图引擎或糟糕的 ejs),我创建了一个 repo,展示了如何在服务器端显示这些图像并使用 ajax: github.com/khrismuc/express-images
标签: javascript html node.js