如何使用管道功能流式传输到AWS S3

问题描述 投票:0回答:1

我想使用 Node.js 原生

pipeline
模块中的
stream
函数将上传流式传输到 AWS S3,但我不知道如何执行此操作。

AWS 的文档展示了如何使用其

Upload
函数上传,但我不确定如何将其转换为可传递到 Node.js 的 pipeline 函数的 WritableStream。

node.js amazon-web-services amazon-s3 stream
1个回答
0
投票

要使用 Node.js 的本机流模块中的管道函数将流式上传到 AWS S3,您可以使用适用于 JavaScript 的 AWS 开发工具包提供的 s3.upload() 方法创建可写流。此方法接受可读流并将其内容上传到指定的 S3 存储桶。尝试这样的方法,看看是否有效,

const { Readable } = require('stream')
const AWS = require('aws-sdk')
const { pipeline } = require('stream')

// configure AWS SDK
AWS.config.update({
  ... relevant credential key value pairs
})

// create an instance of the S3 object
const s3 = new AWS.S3()

// define the source stream (readable stream)
const sourceStream = new Readable()
sourceStream.push('Your data to be uploaded')
sourceStream.push(null) // mark the end of the stream

// define the parameters for S3 upload
const params = {
  Bucket: 'YOUR_BUCKET_NAME',
  Key: 'YOUR_OBJECT_KEY',
  Body: sourceStream
}

// Perform the upload using the pipeline function
pipeline(
  sourceStream,
  s3.upload(params).createWriteStream(),
  (err) => {
    if (err) {
      console.error('Upload failed:', err)
    } else {
      console.log('Upload succeeded')
    }
  }
)
© www.soinside.com 2019 - 2024. All rights reserved.