网站搜索

javascript - 亚马逊 S3 - 在 Node.js 中将字符串通过管道上传到 S3 存储桶中的多个字符串


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

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

我想在我的文件末尾有:

  • 这个计数器为0
  • 这个计数器是1
  • 这个计数器是2

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

    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函数在循环结束时被调用。这个代码没有写入任何数据,为什么?

答案#1

我实际上找到了问题所在。我必须在流结束后发送,而不是在进行时发送。另外也不需要使用管道。

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
  }
}