How to get response from S3 getObject in Node.js?

后端 未结 5 1432
离开以前
离开以前 2020-12-01 04:20

In a Node.js project I am attempting to get data back from S3.

When I use getSignedURL, everything works:

aws.getSignedUrl(\'getObject         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-01 04:54

    Based on the answer by @peteb, but using Promises and Async/Await:

    const AWS = require('aws-sdk');
    
    const s3 = new AWS.S3();
    
    async function getObject (bucket, objectKey) {
      try {
        const params = {
          Bucket: bucket,
          Key: objectKey 
        }
    
        const data = await s3.getObject(params).promise();
    
        return data.Body.toString('utf-8');
      } catch (e) {
        throw new Error(`Could not retrieve file from S3: ${e.message}`)
      }
    }
    
    // To retrieve you need to use `await getObject()` or `getObject().then()`
    getObject('my-bucket', 'path/to/the/object.txt').then(...);
    

提交回复
热议问题