首页 > 解决方案 > 读取文件数组并一一读取Nodejs

问题描述

首先我想说我对 JS 比较陌生,所以我欢迎任何有用的建议。

这是它应该做的:

  1. 读取目录文件
  2. 循环遍历文件数组
  3. 应该:读取文件并将其上传到 s3

它能做什么:

  1. 读取目录文件✅</li>
  2. 循环遍历文件数组✅</li>
  3. 永远不要通过这个:

文件大小为:1 到 2 mb,12 个文件长度或 6 个,无论哪种方式都不起作用。

if (content.length < 1) return console.log("Content < 1")

代码:

async s3() {
        AWS.config.update({
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_KEY,
        })

        const s3 = new AWS.S3()

        const destination = path.join(Utils.getRootPath(), 'uploads', this.email)

        try {
            const files = fs.readdirSync(destination)

            if (!files || files.length == 0) return console.log(`Provided folder '${destination}' is empty or does not exist.`);

            for (const fileName of files) {
                const filePath = path.join(destination, fileName)

                let content = fs.readFileSync(filePath)

                if (content.length < 1) return console.log("Content < 1")

                s3.upload({
                    ACL: 'public-read',
                    Bucket: process.env.AWS_BUCKET_NAME,
                    Key: fileName,
                    Body: fileContent,
                }).promise().then(async (uploadData) => {
                    try {
                        const headData = await s3.headObject({
                            Bucket: process.env.AWS_BUCKET_NAME,
                            Key: fileName,
                        }).promise();
                        return console.log(headData);
                    }
                    catch (err) {
                        console.log(err);
                    }
                })
                console.log(`${fileName} uploaded.`)
            }

        } catch (error) {
            throw new Error(error)
        }

呼叫者:

async container() {
        if (this.email === null) throw new Error('Constructor of Job class is null')

        try {
            await this.placeOrder();
            await Utils.downloadFile(this.email);
            await this.s3();
            return console.log("DONE!")
        }
        catch (err) {
            // return new Error(err);
            // OBRADA OVDE! 
            console.log(err)
        }
    }

标签: node.jsmongodbamazon-web-servicesasynchronousamazon-s3

解决方案


假设我理解正确,有几个问题。首先,不要从for-of循环中返回 when content.length < 1,而应该只是continue. 否则您将不会继续处理剩余的文件。其次,将 promise 和async/await. 您可以await使用s3.upload.

class FileManager {
  async s3() {
    console.log('ok')
    AWS.config.update({
      accessKeyId: process.env.AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.AWS_SECRET_KEY,
    });

    const s3 = new AWS.S3();

    const destination = path.join(Utils.getRootPath(), "uploads", this.email);

    try {
      const files = fs.readdirSync(destination);

      if (!files || files.length == 0)
        return console.log(`Provided folder '${destination}' is empty or does not exist.`);

      for (const fileName of files) {
        const filePath = path.join(destination, fileName);

        let content = fs.readFileSync(filePath);

        if (content.length < 1) {
          console.log("Content < 1");
          continue;
        }

        await s3.upload({
          ACL: "public-read",
          Bucket: process.env.AWS_BUCKET_NAME,
          Key: fileName,
          Body: fileContent,
        });

        try {
          const headData = await s3
            .headObject({
              Bucket: process.env.AWS_BUCKET_NAME,
              Key: fileName,
            })
            .promise();
          console.log(headData);
        } catch (err) {
          console.log(err);
        }

        console.log(`${fileName} uploaded.`);
      }
    } catch (error) {
      throw new Error(error);
    }
  }
}

推荐阅读