【问题标题】:Sending image file from server after filtering the image file name from DB with image files folder使用图像文件夹过滤来自数据库的图像文件名后从服务器发送图像文件
【发布时间】:2021-08-13 21:32:25
【问题描述】:

我创建了一个函数 -

public getImageFile(imageFileName: string) {
 const directoryPath = path.join(__dirname, '../images');

 fs.readdir(directoryPath, (e, images) => {
   if (e) { 
     console.log(e) 
   } 

   const filteredImageFilesArray = images.filter(i => imageFileName.includes(i));

   filteredImageFilesArray.forEach((imageFile) => {
       return imageFileName = imageFile;
   });
 });
}

函数获取一个srting,字符串是来自DB的图像文件名,它将文件名与文件夹进行比较并返回匹配的文件。

我想将文件从服务器发送到客户端。

这是服务器响应 -

  res.status(200).send({
      success: true,
      message: "Successfully retrieved products",
      data: products.map((product) => ({
        id: product.id as string,
        category: {
          value: product.category,
          label: ServerGlobal.getInstance().getCategoryLabel(product.category)!,
        },
        gender: {
          value: product.gender,
          label: ServerGlobal.getInstance().getGenderLabel(product.gender)!,
        },
        title: product.title,
        description: product.description,
        price: product.price,
        imageFileName: ServerGlobal.getInstance().getImageFile(product.imageFileName),
      })),
    });

我在 数据 上遇到错误 -

属性“imageFileName”的类型不兼容。 类型 'void' 不可分配给类型 'string'.ts(2322)

这是我的回复界面-

type IgetProductsResponse = express.Response<
    IServerResponse & {
        data?: {
            id: string;
            category: { value: ProductCategory, label: string };
            gender: { value: ProductGender, label: string };
            title: string;
            description: string;
            price: number;
            imageFileName: File;
        }[];
    }
>;

我能为成功做些什么?

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    您的getImageFile 函数不返回任何内容,即它的返回类型是void,但您正在尝试使用它的返回值。该函数的另一个问题是该函数有一些异步运行的操作(fs.readdir 部分,但是当您调用 ServerGlobal.getInstance().getImageFile(product.imageFileName) 时,您使用它就像是同步代码一样。

    我的另一个问题是 imageFileName: File 中的 File 类型指的是什么。它是string 的别名吗?从错误信息看来是这样的。

    继续前进,我将做以下假设,您希望getImageFile() 函数返回文件名(如果存在),它应该是string。我不确定您是否希望它是同步的或异步的。如果你希望它是同步的,你应该使用fs.readdirSync。但我会继续假设您要使用异步 API。

    如果您坚持使用异步 API,我建议您使用 Promise 和 async/await 以使代码更易于处理并避免回调。

    您可以使用util.promisify 函数将使用回调模式的异步函数转换为使用承诺模式。考虑到这一点,我建议您对代码进行以下更改:

    import { promisify } from "util";
    import { readdir as readdirWithCallback } from "fs";
    
    const readdir = promisify(readdirWithCallback);
    
    async public getImageFile(imageFileName: string): Promise<string> {
     const directoryPath = path.join(__dirname, '../images');
    
     const images = await fs.readdir(directoryPath);
     const foundImage = images.find(i => i === imageFileName);
     return foundImage; // this returns null if the imageFileName was not found
    }
    
    // this should be in a function that has the async keyword
    res.status(200).send({
          success: true,
          message: "Successfully retrieved products",
          data: products.map((product) => ({
            id: product.id as string,
            category: {
              value: product.category,
              label: ServerGlobal.getInstance().getCategoryLabel(product.category)!,
            },
            gender: {
              value: product.gender,
              label: ServerGlobal.getInstance().getGenderLabel(product.gender)!,
            },
            title: product.title,
            description: product.description,
            price: product.price,
            // notice the await here, because this is function that returns a promise
            imageFileName: await ServerGlobal.getInstance().getImageFile(product.imageFileName),
          })),
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多