【问题标题】:In Node/Javascript, how to load all images from directory and display在 Node/Javascript 中,如何从目录加载所有图像并显示
【发布时间】: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


【解决方案1】:

一个简单而经典的方法是这样的:

后端:

import { promises } from "fs";

app.get('/', async (req, res) => {
    try {
        const files = await promises.readdir(directoryPath);
        res.status(200).json(files);
    } catch (err) {
        res.status(500).json(err);
    }
});

前端:

let files;
try{
    const response = await fetch("/");
    files = await response.json();
    // files is now an array of file names, do what you want with that (create <img> tags, etc.)
} catch(err){
    console.error(err)
}

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 2013-03-17
    • 2013-07-12
    • 2012-07-02
    • 2023-03-10
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    相关资源
    最近更新 更多