Pesquisa de site

javascript - Amazon S3 - Encaminhar uma string para enviar várias strings para um Bucket S3 no nodejs


Vamos supor que eu tenha um loop simples assim:

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

Eu quero ter no meu arquivo no final:

  • Este contador é 0
  • Este contador é 1
  • Este contador é 2

Tentei fazer isso fazendo isto :

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

Minha função init é chamada no início do loop, minha função to é chamada toda vez que quero inserir uma string no arquivo e a função finish no final do loop. Este código não insere nenhum dado, por quê?

Resposta #1

Na verdade, eu descobri qual era o problema. Eu tive que enviar o fluxo depois que ele terminou e não enquanto eu estava fazendo. Além disso, não há necessidade de pipe.

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