【问题标题】:Amazon S3 - Pipe a string to upload multiple string on S3 Bucket in nodejsAmazon S3 - 管道字符串以在 nodejs 中的 S3 存储桶上上传多个字符串
【发布时间】:2021-11-20 02:00:12
【问题描述】:

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


    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 函数在每次我想在文件中推送一个字符串时被调用,而 在循环结束时完成函数。这段代码没有推送任何数据,为什么?

【问题讨论】:

    标签: javascript node.js typescript amazon-s3 node-streams


    【解决方案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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2018-09-29
      • 2021-08-03
      • 1970-01-01
      • 2018-04-12
      • 2014-02-26
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多