Created
August 27, 2021 21:44
-
-
Save Angelfire/968109c5ced612b318a66c329104af1a to your computer and use it in GitHub Desktop.
Download object from S3 bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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