Amazon S3 - 管道字符串以在 nodejs 中的 S3 Bucket 上上传多个字符串

Amazon S3 - Pipe a string to upload multiple string on S3 Bucket in nodejs

假设我有一个像这样的简单循环:


    for (const i=0;i<3;i++) {
        to(`This counter is ${i}`)
    }

我想在我的文件末尾加入:

我试图通过这样做来做到这一点:


    export class S3Output extends Output {
      #stream: Readable | null = null
      async to(s: string): Promise<void> {
        const params = {
          Bucket: config.aws.bucketName,
          Body: this.#stream,
          Key: 'test.json'
        }
        this.#stream?.pipe(process.stdout)
        this.#stream?.push(s)
        await S3.upload(params).promise()
        return
      }
    
      init(): void {
        this.#stream = new Readable()
        this.#stream._read = function () {};
      }
    
      finish(): void {
        this.#stream?.push(null)
        return
      }
    }

我的init函数在循环开始时被调用,我的to函数在每次我想压入一个字符串时被调用在文件中和循环结束时的 finish 函数。此代码不推送任何数据,为什么?

我真的找到了问题所在。我必须在流结束后发送流,而不是在我这样做的时候。也不需要管道。

export class S3Output extends Output {
  #stream: Readable | null = null
  async to(s: string): Promise<void> {
    this.#stream?.push(s)
    return
  }

  init(): void {
    this.#stream = new Readable()
    this.#stream._read = function () {}
  }

  async finish(): Promise<void> {
    this.#stream?.push(null)
    const params = {
      Bucket: config.aws.bucketName,
      Body: this.#stream,
      Key: 'test.json'
    }
    await S3.upload(params).promise()
    return
  }
}