Skip to content

Instantly share code, notes, and snippets.

@Angelfire
Created August 27, 2021 21:44
Show Gist options
  • Save Angelfire/968109c5ced612b318a66c329104af1a to your computer and use it in GitHub Desktop.
Save Angelfire/968109c5ced612b318a66c329104af1a to your computer and use it in GitHub Desktop.
Download object from S3 bucket
const { s3, GetObjectCommand } = require('./s3Client')
// convert a ReadableStream to a string
const streamToString = (stream) =>
new Promise((resolve, reject) => {
const chunks = []
stream.on('data', (chunk) => chunks.push(chunk))
stream.on('error', reject)
// stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
stream.once('end', () => resolve(chunks.join('')))
})
const handleDownload = async (objectKey) => {
const params = {
Bucket: 'dev-ts-apimg',
Key: `profiles/${objectKey}`
}
try {
const command = new GetObjectCommand(params)
const data = await s3.send(command)
const bodyContents = await streamToString(data.Body)
return bodyContents
} catch (err) {
console.error(err)
}
}
module.exports = handleDownload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment