fs.readDirSync 不返回文件夹中的文件

问题描述 投票:0回答:1

我有一个由几个方法组成的小类。

export class imageHandler {
  id: string;
  imageFolder: string;
  jobFolder: string;
  bucket: Bucket;

  constructor(id: string, imageFolder: string) {
    this.id = id;
    this.imageFolder = imageFolder;
    this.bucket = new Bucket();

    //Creates the Job Directory and stores it in the variable.
    fs.mkdirSync(`${imageFolder}/${id}`, { recursive: true });
    this.jobFolder = `${imageFolder}/${id}`;
  }

  async saveImages(urls: string[]) {
    await getImages(urls, this.jobFolder)
  }

  async uploadImages() {
    const images = fs.readdirSync(this.jobFolder);
    console.log("These are the Images: ", images);
    console.log("This is the Job Folder", this.jobFolder);
  }
}

saveImages()
方法调用
getImages()
函数,该函数从列表中下载图像并将其保存在
jobFolder
目录中。 图像下载完成后,我想调用
uploadImages()
方法,该方法将从
jobFolder
中获取文件并将其上传到
S3
存储桶。 但是,
FS.readDirSync()
在文件夹中找不到任何图像。并返回一个空的
Array
。 这是我的
Main
函数。

const main = async (url: string) => {
  const id = uid(5);
  const IH = new imageHandler(id, imageFolder);

  await IH.saveImages(data?.images).then((val) => {
    IH.uploadImages();
  });
};

我知道图像正在下载并保存,因为我可以看到图像。但我的程序在运行时看不到它们。我可以做什么来解决这个问题? 这是我的

getImages()
函数。

export const getImages = async (
  links: string[],
  folder: string,
  extra?: string
) => {
  links.forEach(async (link, i) => {
    const fileLocation = path.resolve(
      folder,
      extra ? extra : "",
      `image${i}.jpeg`
    );

    await axios({
      method: "get",
      url: extractImageUrl(link),
      responseType: "stream",
    }).then(function (response) {
      response.data
        .pipe(new ExifTransformer())
        .pipe(fs.createWriteStream(fileLocation));
    });
  });
};

谁能帮我解决这个问题吗?谢谢你。

node.js file async-await filesystems node.js-fs
1个回答
0
投票

删除异步代码中对

.forEach()
的所有使用。它不具有 Promise 意识,并且不会等待其回调函数中的
await

相反,将其替换为常规的

for
循环。

而且,您还必须找到一种方法来等待

.pipe()
完成,否则您的
async
函数将在完成之前返回。

并且,不要混合

await
.then()
,因为这会导致代码可读性大大降低。

export const getImages = async (
    links: string[],
    folder: string,
    extra?: string
) => {
    for (const [i, index] of links.entries())
        const fileLocation = path.resolve(
            folder,
            extra ? extra : "",
            `image${i}.jpeg`
        );

        const response = await axios({
            method: "get",
            url: extractImageUrl(link),
            responseType: "stream",
        });
        await new Promise((resolve, reject) => {
            response.data
                .pipe(new ExifTransformer())
                .pipe(fs.createWriteStream(fileLocation))
                .on("error", reject)
                .on("finish", resolve);
        });
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.